Preserve installed operator workspace before consolidation

Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 09:59:51 +03:00
parent 97614742bb
commit d0e5f90952
368 changed files with 129172 additions and 1856 deletions
@@ -0,0 +1,38 @@
[
{
"repository": "dwang-LI/segformer-b0-finetuned-segments-sidewalk-2",
"revision": "e0eb6fad999c90c7cf8138189a7ddb9406f956f2",
"asset_directory": "segments-b2",
"qualification_only": true,
"files": {
"config.json": "dd16ffdbbc51f392ef9641bbbc59a3fa720b07e2ff818554e2063341b907c9cc",
"preprocessor_config.json": "e5a25d8fc054bf780be930e161b47d188bec1b0bf0a44fd5fdfb3f3312c0be0b",
"README.md": "67a2485e3d97e7b24b1419e2f2a5d24f2c2dec435fd4ded970d800be2e13bd95",
"pytorch_model.bin": "d89fa68bb6d716b628e9e3960ada7852e7d656959a0402faa5ad0e94478ad015"
}
},
{
"repository": "nickmuchi/segformer-b4-finetuned-segments-sidewalk",
"revision": "a8ca92dc8795137a2c54e00ada2c4dbcdfa79be0",
"asset_directory": "segments-b4",
"qualification_only": true,
"files": {
"config.json": "97d72bc0904263ec0a2b69fa27cb5f1fc1d6c2d82841f733363b1a0ff7296ca7",
"preprocessor_config.json": "d96ab2cb112985c19d5ea32f1d1f2369104fc78b1379f5ce26e33ca8646202a7",
"README.md": "e8c5057f08c9958e2bdb08e092d038b3ce1ac27c1964330a265279796e98414c",
"pytorch_model.bin": "a2ea012536bac413eed20899998444081154ceb4f6d09845e1826910a51960c1"
}
},
{
"repository": "tobiasc/segformer-b0-finetuned-segments-sidewalk",
"revision": "bd7ac387735e41f8c48e253a0227047b1bf9f552",
"asset_directory": "segments-b0",
"qualification_only": true,
"files": {
"config.json": "3d6331be24914e553798602362e8529240a0bb1fb1b9696845cc8031eedfd339",
"preprocessor_config.json": "8039d1d210abaa7117ad78e58cdfd6141a2ec72c03dae891b3cd76737e422c6c",
"README.md": "9d2acbbc46c412e2a94ba5ca0c02a4f43954e020c20a188d0e8778aafc205760",
"model.safetensors": "da0498037a44ec0b335ca7c96fe2422cac4d28550cd09df80f71c557bf0e027e"
}
}
]
@@ -0,0 +1,53 @@
"""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"))
args = parser.parse_args()
for descriptor in json.loads(Path(__file__).with_name("models.json").read_text()):
prepare(args.root, descriptor)
def prepare(root, descriptor):
output = root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
output.mkdir(parents=True, exist_ok=True)
for name, expected in descriptor["files"].items():
path = output / name
if not path.exists():
part = path.with_name(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,90 @@
"""Compare pinned pedestrian-trained models on immutable recorded RGB frames."""
import hashlib
import json
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from transformers import AutoImageProcessor, SegformerConfig, SegformerForSemanticSegmentation
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 main():
torch.set_num_threads(3)
output = Path('/evidence')
rows = []
sources = json.loads(Path('/inputs/manifest.json').read_text())
for descriptor in json.loads(Path('/adapter/models.json').read_text()):
key = descriptor['asset_directory']
assets = Path('/assets') / key / descriptor['revision']
for name, digest in descriptor['files'].items():
assert sha(assets / name) == digest, name
processor = AutoImageProcessor.from_pretrained(assets, local_files_only=True)
model = SegformerForSemanticSegmentation(SegformerConfig.from_pretrained(assets, local_files_only=True))
if (assets / 'model.safetensors').exists():
from safetensors.torch import load_file
state = load_file(str(assets / 'model.safetensors'))
else:
state = torch.load(assets / 'pytorch_model.bin', map_location='cpu', weights_only=True)
model.load_state_dict(state, strict=True)
del state
model.cuda().eval()
for source in sources:
path = Path('/inputs') / source['file']
assert sha(path) == source['sha256']
original = Image.open(path).convert('RGB')
for crop in (True, False):
# Same central square used by the navigation RPC, plus full-view context.
side = min(original.size)
x = (original.width - side) // 2
y = (original.height - side) // 2
image = original.crop((x, y, x + side, y + side)) if crop else original
inputs = processor(images=image, return_tensors='pt').to('cuda')
torch.cuda.reset_peak_memory_stats()
torch.cuda.synchronize()
begin = time.monotonic()
with torch.inference_mode():
logits = model(**inputs).logits
logits = torch.nn.functional.interpolate(logits, size=(image.height, image.width), mode='bilinear', align_corners=False)
confidence, labels = logits.softmax(dim=1).max(dim=1)
labels = labels[0].cpu().numpy().astype(np.uint8)
known = confidence[0].cpu().numpy() >= .55
torch.cuda.synchronize()
elapsed = time.monotonic() - begin
name = f"{key}-{path.stem}-{'crop' if crop else 'full'}"
Image.fromarray(labels).save(output / (name + '.labels.png'))
Image.fromarray((known * 255).astype(np.uint8)).save(output / (name + '.known.png'))
colors = np.zeros((*labels.shape, 3), dtype=np.uint8)
colors[(labels == 2) & known] = [20, 220, 170]
colors[(labels == 1) & known] = [220, 40, 50]
colors[(labels == 3) & known] = [240, 200, 20]
Image.blend(image, Image.fromarray(colors), .45).save(output / (name + '.jpg'))
ids, counts = np.unique(labels, return_counts=True)
row = dict(case=name, model_revision=descriptor['revision'], source=source,
utc=datetime.now(timezone.utc).isoformat(), monotonic=time.monotonic(),
inference_seconds=elapsed, input_shape=list(inputs['pixel_values'].shape),
gpu_peak_bytes=torch.cuda.max_memory_allocated(),
pedestrian_fraction=float(((labels == 2) & known).mean()),
road_fraction=float(((labels == 1) & known).mean()),
classes={model.config.id2label[int(i)]: int(n) for i, n in zip(ids, counts)})
rows.append(row)
(output / 'results.json').write_text(json.dumps(rows, indent=2))
print(json.dumps({k:row[k] for k in ('case','inference_seconds','pedestrian_fraction','road_fraction')}), flush=True)
del model, inputs, logits
torch.cuda.empty_cache()
(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,57 @@
"""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("--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()
assets = args.root / "assets"
for descriptor in json.loads((adapter / "models.json").read_text()):
assert (assets / descriptor["asset_directory"] / descriptor["revision"] / "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-sidewalk-qualification-" + receipt["owner_id"][-8:],
"--gpus", "all", "--cpus", "3", "--memory", "6g",
"--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",
"--entrypoint", "/opt/conda/envs/goose/bin/python",
"sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536",
"-B", "/adapter/qualify.py",
], 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()