Files
NODEDC_MISSION_CORE/simulation/ai-polygon/sam3-research/qualify.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

110 lines
5.6 KiB
Python

"""Qualify SAM3-LiteText on recorded RGB; instance masks grant no motion authority."""
import hashlib
import argparse
import json
import time
from datetime import datetime, timezone
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
PROMPTS = ('sidewalk', 'roadway', 'crosswalk', 'wall')
def sha(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024*1024), b''):
digest.update(chunk)
return digest.hexdigest()
def load_exact(model, path):
"""Apply the author's key normalization, but reject missing model parameters."""
state = torch.load(path, map_location='cpu', weights_only=True)
state = state.get('model', state)
# The pinned ctx16 checkpoint already contains truncated positional
# embeddings, whereas the author's builder initially allocates ctx77.
# Resize the architecture before strict loading; do not pad learned weights.
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:
assert normalized not in selected
selected[normalized] = value
model.load_state_dict(selected, strict=True)
print('Exact model parameter load accepted', len(selected), flush=True)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--confidence', type=float, default=.5)
parser.add_argument('--prompts', nargs='+', default=PROMPTS)
parser.add_argument('--descriptor', type=Path, default=Path('/adapter/model.json'))
args = parser.parse_args()
if not 0 < args.confidence < 1:
raise ValueError('Invalid confidence threshold')
torch.set_num_threads(3)
assets=Path('/assets');output=Path('/evidence')
descriptor=json.loads(args.descriptor.read_text())
for name, expected in descriptor['files'].items():
assert sha(assets/name)==expected, name
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.get('text_encoder', 'MobileCLIP-S1'),text_encoder_context_length=16,device='cuda')
processor=Sam3Processor(model,device='cuda',confidence_threshold=args.confidence)
(output/'method.json').write_text(json.dumps(dict(
descriptor=descriptor, prompts=args.prompts, confidence=args.confidence,
authority='offline RGB qualification; no motion permission'), indent=2))
rows=[]
for source in json.loads(Path('/inputs/manifest.json').read_text()):
path=Path('/inputs')/source['file'];assert sha(path)==source['sha256']
image=Image.open(path).convert('RGB')
torch.cuda.synchronize();begin=time.monotonic()
masks={};scores={};times={};confidence_rasters={}
with torch.inference_mode(), torch.autocast('cuda',dtype=torch.bfloat16):
state=processor.set_image(image)
torch.cuda.synchronize();encode_time=time.monotonic()-begin
for prompt in args.prompts:
start=time.monotonic()
state=processor.set_text_prompt(prompt,state)
selected=state['masks'].reshape(-1,image.height,image.width)
union=selected.any(dim=0).cpu().numpy() if len(selected) else np.zeros((image.height,image.width),bool)
masks[prompt]=union;scores[prompt]=state['scores'].float().cpu().tolist()
# Retain per-pixel instance confidence for offline threshold
# comparisons. This is not a calibrated class probability and
# never supplies runtime permission or ground truth.
confidence = np.zeros((image.height, image.width), dtype=np.float32)
for mask, score in zip(selected.cpu().numpy(), scores[prompt], strict=True):
np.maximum(confidence, np.where(mask, score, 0), out=confidence)
confidence_rasters[prompt] = confidence
torch.cuda.synchronize();times[prompt]=time.monotonic()-start
Image.fromarray((union*255).astype(np.uint8)).save(output/(path.stem+'.'+prompt+'.png'))
elapsed=time.monotonic()-begin
np.savez_compressed(output/(path.stem+'.confidence.npz'), **confidence_rasters)
colors=np.zeros((image.height,image.width,3),np.uint8)
colors[masks['sidewalk']]=[20,220,170];colors[masks['roadway']]=[220,40,50]
colors[masks['crosswalk']]=[240,200,20]
colors[masks['sidewalk']&masks['roadway']]=[255,0,255]
Image.blend(image,Image.fromarray(colors),.45).save(output/(path.stem+'.jpg'))
row=dict(source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),
inference_seconds=elapsed,image_encoder_seconds=encode_time,prompt_seconds=times,
fractions={k:float(v.mean()) for k,v in masks.items()},scores=scores,
road_sidewalk_overlap=float((masks['sidewalk']&masks['roadway']).mean()))
rows.append(row);(output/'results.json').write_text(json.dumps(rows,indent=2))
print(json.dumps(row),flush=True)
(output/'artifact-sha256.json').write_text(json.dumps({p.name:sha(p) for p in output.iterdir() if p.is_file()},indent=2))
if __name__=='__main__':
main()