Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
FROM ndc-sam3-litetext-qualification:0705589032d7
|
||||
COPY environment /opt/env
|
||||
COPY source /source
|
||||
COPY build-inputs.json /sam3-build-inputs.json
|
||||
ENV PYTHONPATH=/adapter/src:/source:/opt/samdeps:/opt/env
|
||||
LABEL com.nodedc.product="mission-core" \
|
||||
com.nodedc.stack="ai-polygon" \
|
||||
com.nodedc.role="sam3-segmentation" \
|
||||
com.nodedc.managed-by="ai-polygon-worker"
|
||||
ENTRYPOINT ["python3", "-B", "/adapter/simulation/ai-polygon/sam3/server.py"]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Seal the qualified Python closure and upstream source into a model image.
|
||||
|
||||
Only copies the existing artifact-owned environment into bounded build staging.
|
||||
No installation into Windows/WSL or mutation of the source environment.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--runtime', type=Path, default=Path('D:/NDC_MISSIONCORE/runtime'))
|
||||
args = parser.parse_args()
|
||||
assert not (args.runtime / 'simulation/state/active.json').exists()
|
||||
base = 'ndc-sam3-litetext-qualification:0705589032d7'
|
||||
expected = 'sha256:6a1a2f2e4ebe499b648b9f75bdacf47ef36a2128a0ec8385b6decdc770f21e6c'
|
||||
actual = json.loads(subprocess.check_output(['docker', 'image', 'inspect', base], text=True))[0]['Id']
|
||||
assert actual == expected, 'Build predecessor changed'
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
context = args.output / 'context'; context.mkdir()
|
||||
source_archive = args.runtime / 'simulation/staging/source.tar.gz'
|
||||
assert sha(source_archive) == 'bdac58424bcb39e2533689b3256ba52e15f612472a7bbc05a0485de5017da576'
|
||||
with tarfile.open(source_archive) as archive:
|
||||
archive.extractall(context / 'upstream', filter='data')
|
||||
upstream = context / 'upstream/efficientsam3-bd0936c788fed8d51fa799437f05abd97b401b06/sam3'
|
||||
shutil.move(str(upstream), str(context / 'source'))
|
||||
shutil.rmtree(context / 'upstream')
|
||||
closure = args.runtime / 'derived/perception-p0-env-v1'
|
||||
size = sum(p.stat().st_size for p in closure.rglob('*') if p.is_file())
|
||||
assert shutil.disk_usage(args.output).free > size * 3 + 10 * 1024**3
|
||||
shutil.copytree(closure, context / 'environment', ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
|
||||
shutil.copyfile(Path(__file__).with_name('Dockerfile'), context / 'Dockerfile')
|
||||
inputs = {p.relative_to(context).as_posix(): sha(p) for p in sorted(context.rglob('*')) if p.is_file()}
|
||||
encoded = json.dumps(dict(base=expected, files=inputs), sort_keys=True).encode()
|
||||
(context / 'build-inputs.json').write_bytes(encoded)
|
||||
tag = 'ndc-sam3-surfaces:' + hashlib.sha256(encoded).hexdigest()[:16]
|
||||
with (args.output / 'build.log').open('w') as log:
|
||||
subprocess.run(['docker', 'build', '--pull=false', '-t', tag, str(context)],
|
||||
env={**os.environ, 'DOCKER_BUILDKIT':'0'}, stdout=log, stderr=subprocess.STDOUT,
|
||||
check=True, timeout=900)
|
||||
identity = json.loads(subprocess.check_output(['docker', 'image', 'inspect', tag], text=True))[0]['Id']
|
||||
receipt = dict(image=identity, tag=tag, input_sha256=hashlib.sha256(encoded).hexdigest(),
|
||||
source_archive_sha256=sha(source_archive), runtime_changes='none; isolated image only')
|
||||
(args.output / 'image.json').write_text(json.dumps(receipt, indent=2))
|
||||
shutil.copyfile(context / 'build-inputs.json', args.output / 'build-inputs.json')
|
||||
shutil.rmtree(context)
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"repository": "Simon7108528/EfficientSAM3",
|
||||
"revision": "85b05896928f974e308f889d7ccb2eefc069de98",
|
||||
"asset_directory": "sam3-litetext-s1",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"sam3_litetext/sam3_litetext_mobileclip_s1_ctx16.pt": "2cb918109a0082292cb414f48ae077f4351a56279f05ab67d56adc8b24f21731"
|
||||
},
|
||||
"text_encoder": "MobileCLIP-S1",
|
||||
"confidence_thresholds": {
|
||||
"sidewalk": 0.3,
|
||||
"roadway": 0.5,
|
||||
"crosswalk": 0.5,
|
||||
"wall": 0.5
|
||||
},
|
||||
"operating_point_status": "candidate: RGB replay, requires closed-loop qualification; scores are not calibrated probabilities"
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Pinned SAM3-LiteText RGB provider; no world labels, routes or permission input."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
import sam3.model_builder as builder
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
|
||||
from k1link.simulation.ai_polygon.concept_surfaces import PROMPTS, concept_rasters
|
||||
|
||||
|
||||
def load_exact(model, path):
|
||||
state = torch.load(path, map_location="cpu", weights_only=True)
|
||||
state = state.get("model", state)
|
||||
# This pinned checkpoint is already ctx16. Allocate its exact architecture
|
||||
# before loading, rather than padding weights or dropping missing keys.
|
||||
model.backbone.language_backbone.set_context_length(16)
|
||||
expected = set(model.state_dict())
|
||||
selected = {}
|
||||
for key, value in state.items():
|
||||
normalized = key.removeprefix("detector.").replace("student_trunk.", "")
|
||||
if normalized in expected:
|
||||
if normalized in selected:
|
||||
raise ValueError("Duplicate model parameter")
|
||||
selected[normalized] = value
|
||||
model.load_state_dict(selected, strict=True)
|
||||
|
||||
|
||||
def main():
|
||||
descriptor = json.loads(Path(__file__).with_name("model.json").read_text())
|
||||
assets = Path("/assets")
|
||||
for name, expected in descriptor["files"].items():
|
||||
with (assets / name).open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
|
||||
raise RuntimeError("SAM3 asset identity changed")
|
||||
torch.set_num_threads(3)
|
||||
builder._load_checkpoint = load_exact
|
||||
model = builder.build_sam3_image_model(
|
||||
bpe_path="/source/assets/bpe_simple_vocab_16e6.txt.gz",
|
||||
checkpoint_path=str(assets / next(iter(descriptor["files"]))),
|
||||
load_from_HF=False, enable_segmentation=True, enable_inst_interactivity=False,
|
||||
compile=False, text_encoder_type=descriptor["text_encoder"],
|
||||
text_encoder_context_length=16, device="cuda")
|
||||
thresholds = descriptor["confidence_thresholds"]
|
||||
if (set(thresholds) != set(PROMPTS)
|
||||
or any(type(x) not in (int, float) or not 0 < x < 1
|
||||
for x in thresholds.values())):
|
||||
raise ValueError("Invalid concept confidence thresholds")
|
||||
processor = Sam3Processor(model, device="cuda", confidence_threshold=min(thresholds.values()))
|
||||
|
||||
def infer(rgb):
|
||||
masks = {}
|
||||
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
state = processor.set_image(Image.fromarray(rgb))
|
||||
for prompt in PROMPTS:
|
||||
state = processor.set_text_prompt(prompt, state)
|
||||
found = state["masks"].reshape(-1, 600, 800)
|
||||
found = found[state["scores"].reshape(-1) >= thresholds[prompt]]
|
||||
masks[prompt] = (found.any(dim=0).cpu().numpy() if len(found)
|
||||
else np.zeros((600, 800), dtype=bool))
|
||||
return b"".join(plane.astype(np.uint8).tobytes()
|
||||
for plane in concept_rasters(masks))
|
||||
|
||||
infer(np.zeros((600, 800, 3), dtype=np.uint8))
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(10)
|
||||
|
||||
def reply(self, status, body):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
self.reply(200 if self.path == "/ready" else 404,
|
||||
json.dumps({"model": "sam3-litetext-surfaces"}).encode())
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/infer" or self.headers.get("Content-Length") != "1440000":
|
||||
self.reply(400, b"Expected 800x600 RGB uint8")
|
||||
return
|
||||
try:
|
||||
raw = self.rfile.read(1440000)
|
||||
if len(raw) != 1440000:
|
||||
raise ValueError("Incomplete camera frame")
|
||||
self.reply(200, infer(np.frombuffer(raw, np.uint8).reshape(600, 800, 3)))
|
||||
except (TimeoutError, ValueError, RuntimeError):
|
||||
self.reply(500, b"Concept segmentation failed")
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
HTTPServer(("0.0.0.0", 8010), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user