Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
FROM ndc/mission-core-ai-module-eomt:20260904-v8
|
||||
COPY requirements.txt /qualification-requirements.txt
|
||||
RUN python3 -m pip install --no-deps --no-cache-dir --target /opt/samdeps --report /samdeps-install.json -r /qualification-requirements.txt
|
||||
ENV PYTHONPATH=/source:/opt/samdeps:/opt/transformers:/opt/env
|
||||
LABEL com.nodedc.product="mission-core" \
|
||||
com.nodedc.stack="ai-polygon-qualification" \
|
||||
com.nodedc.role="sam3-litetext-qualification" \
|
||||
com.nodedc.managed-by="ai-polygon-qualification"
|
||||
ENTRYPOINT ["python3"]
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"repository": "Simon7108528/EfficientSAM3",
|
||||
"revision": "85b05896928f974e308f889d7ccb2eefc069de98",
|
||||
"asset_directory": "sam3-litetext-l",
|
||||
"text_encoder": "MobileCLIP2-L",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"sam3_litetext/sam3_litetext_mobileclip2_l_ctx16.pt": "e46d12107c572ec0ec4b98a9ba940864cd7c489b07e06ed010888318cc0fd3ab"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"repository": "Simon7108528/EfficientSAM3",
|
||||
"revision": "85b05896928f974e308f889d7ccb2eefc069de98",
|
||||
"asset_directory": "sam3-litetext-s1",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"sam3_litetext/sam3_litetext_mobileclip_s1_ctx16.pt": "2cb918109a0082292cb414f48ae077f4351a56279f05ab67d56adc8b24f21731"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Prepare only the pinned optional research model; no host packages or services."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
parser.add_argument('--descriptor', type=Path, default=Path(__file__).with_name('model.json'))
|
||||
args = parser.parse_args()
|
||||
descriptor = json.loads(args.descriptor.read_text())
|
||||
output = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for name, expected in descriptor["files"].items():
|
||||
path = output / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not path.exists():
|
||||
part = path.with_name(path.name + f".{os.getpid()}.part")
|
||||
url = f'https://huggingface.co/{descriptor["repository"]}/resolve/{descriptor["revision"]}/{name}'
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response, part.open("xb") as stream:
|
||||
while chunk := response.read(1024 * 1024):
|
||||
stream.write(chunk)
|
||||
if sha(part) != expected:
|
||||
raise ValueError("Downloaded model checksum mismatch: " + name)
|
||||
part.replace(path)
|
||||
finally:
|
||||
part.unlink(missing_ok=True)
|
||||
if sha(path) != expected:
|
||||
raise ValueError("Existing model checksum mismatch: " + name)
|
||||
receipt = dict(schema_version="missioncore.optional-model-preparation/v1",
|
||||
descriptor=descriptor, utc=datetime.now(UTC).isoformat(),
|
||||
assets=str(output), scope="offline simulation qualification",
|
||||
rollback="Remove this optional qualification asset; no active model was changed")
|
||||
(output / "installation.json").write_text(json.dumps(receipt, indent=2))
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Read-only dependency probe; no model weights, GPU or rover access."""
|
||||
import importlib,importlib.metadata,json,sys
|
||||
result={'python':sys.version}
|
||||
for name in ['torch','torchvision','timm','numpy','iopath','ftfy','einops','decord','torchcodec','pycocotools','cv2','scipy','psutil','triton','huggingface_hub']:
|
||||
try:
|
||||
m=importlib.import_module(name);result[name]=getattr(m,'__version__','present')
|
||||
except Exception as e:result[name]=str(e)
|
||||
print(json.dumps(result))
|
||||
try:
|
||||
from sam3.model_builder import build_sam3_image_model
|
||||
print('builder import OK')
|
||||
except Exception:
|
||||
import traceback;traceback.print_exc();raise
|
||||
@@ -0,0 +1,109 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,10 @@
|
||||
timm==1.0.22
|
||||
ftfy==6.1.1
|
||||
iopath==0.1.10
|
||||
portalocker==3.2.0
|
||||
wcwidth==0.2.14
|
||||
einops==0.8.1
|
||||
psutil==7.1.0
|
||||
pycocotools==2.0.10
|
||||
decord==0.6.0
|
||||
opencv-python-headless==4.11.0.86
|
||||
@@ -0,0 +1,65 @@
|
||||
"""One offline GPU job under a Core simulation reservation, with exact cleanup."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--reservation", type=Path, required=True)
|
||||
parser.add_argument("--inputs", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument('--confidence', type=float, default=.5)
|
||||
parser.add_argument('--descriptor', default='model.json', choices=['model.json', 'large-model.json'])
|
||||
parser.add_argument('--prompts', nargs='+', default=['sidewalk', 'roadway', 'crosswalk', 'wall'])
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
receipt = json.loads(args.reservation.read_text())
|
||||
assert receipt["state"] == "reserved" and receipt["owner_id"].startswith("airun-")
|
||||
assert not (args.root / "state/active.json").exists(), "A rover run is active"
|
||||
assert 0 <= (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds() < 900
|
||||
adapter = Path(__file__).parent.resolve()
|
||||
descriptor = json.loads((adapter / args.descriptor).read_text())
|
||||
assets = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
assert (assets / "installation.json").is_file()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
identity = None
|
||||
begin = time.monotonic()
|
||||
try:
|
||||
identity = subprocess.check_output([
|
||||
"docker", "run", "-d", "--name", "ndc-sam3-qualification-" + receipt["owner_id"][-8:],
|
||||
"--gpus", "all", "--cpus", "3", "--memory", "12g",
|
||||
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon-qualification",
|
||||
"--label", "com.nodedc.role=qualification", "--label", "com.nodedc.managed-by=ai-polygon-qualification",
|
||||
"--mount", f"type=bind,source={adapter},target=/adapter,readonly",
|
||||
"--mount", f"type=bind,source={assets},target=/assets,readonly",
|
||||
"--mount", f"type=bind,source={args.inputs.resolve()},target=/inputs,readonly",
|
||||
"--mount", f"type=bind,source={args.output.resolve()},target=/evidence",
|
||||
"--mount", "type=bind,source=D:/NDC_MISSIONCORE/runtime/derived/perception-p0-env-v1,target=/opt/env,readonly",
|
||||
"--mount", "type=bind,source=D:/NDC_MISSIONCORE/runtime/derived/perception-p0-transformers4576-v1,target=/opt/transformers,readonly",
|
||||
"--mount", f"type=bind,source={adapter.parent / 'source/efficientsam3-bd0936c788fed8d51fa799437f05abd97b401b06/sam3'},target=/source,readonly",
|
||||
"--entrypoint", "python3",
|
||||
"sha256:6a1a2f2e4ebe499b648b9f75bdacf47ef36a2128a0ec8385b6decdc770f21e6c",
|
||||
"-B", "/adapter/qualify.py",
|
||||
'--descriptor', '/adapter/' + args.descriptor,
|
||||
'--confidence', str(args.confidence), '--prompts', *args.prompts,
|
||||
], text=True).strip()
|
||||
result = subprocess.check_output(["docker", "wait", identity], timeout=600, text=True).strip()
|
||||
logs = subprocess.check_output(["docker", "logs", identity], stderr=subprocess.STDOUT, text=True)
|
||||
(args.output / "execution.log").write_text(logs)
|
||||
print(logs[-14000:])
|
||||
assert result == "0", "Model qualification failed: exit " + result
|
||||
finally:
|
||||
released = identity is None or subprocess.run(["docker", "rm", "-f", identity], capture_output=True).returncode == 0
|
||||
(args.output / "cleanup.json").write_text(json.dumps(dict(
|
||||
owner_id=receipt["owner_id"], released=released, utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - begin)))
|
||||
assert released
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"url": "https://codeload.github.com/SimonZeng7108/efficientsam3/tar.gz/bd0936c788fed8d51fa799437f05abd97b401b06",
|
||||
"revision": "bd0936c788fed8d51fa799437f05abd97b401b06",
|
||||
"sha256": "bdac58424bcb39e2533689b3256ba52e15f612472a7bbc05a0485de5017da576"
|
||||
}
|
||||
Reference in New Issue
Block a user