Files
NODEDC_MISSION_CORE/simulation/ai-polygon/sam3/server.py
T

113 lines
4.7 KiB
Python

"""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, FixedConceptTextEncoder, 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")
# Encoding depends only on these fixed prompts and the immutable weights.
# Warmup below populates the bounded cache under the same inference/autocast
# context as live frames. Image features and masks are never cached.
model.backbone.forward_text = FixedConceptTextEncoder(model.backbone.forward_text, "cuda")
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()