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,16 @@
{
"repository": "CIDAS/clipseg-rd64-refined",
"revision": "999e0328d9e10b484360c477313983f9afdd7050",
"asset_directory": "clipseg-rd64-refined",
"qualification_only": true,
"files": {
"config.json": "c023375966d31b3b1392764f7bd91df47098ce19f62f11b0263d8eedcf708bcd",
"preprocessor_config.json": "4fb09ebcfd7651205ca8299b993c30088e5535ef350a72d46c5c4580eeac0440",
"tokenizer_config.json": "4c75d57fd9bd0be8478ad2d6f8b9cebdd4a45338eb108547329c2b6333476ca6",
"special_tokens_map.json": "c4864a9376a8401918425bed71fc14fc0e81f9b59ec45c1cf96cccb2df508eac",
"vocab.json": "e089ad92ba36837a0d31433e555c8f45fe601ab5c221d4f607ded32d9f7a4349",
"merges.txt": "9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a",
"README.md": "c1e26ac022542015a04d804460bdc1159d753c4349b628e086f127475d2fcf25",
"pytorch_model.bin": "dd9308225b8314bb7236f207e6ea72b22db5d90dba03fe3dc7d654f54dcfd08a"
}
}
@@ -0,0 +1,49 @@
"""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()
descriptor = json.loads(Path(__file__).with_name("model.json").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
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,74 @@
"""Text-conditioned segmentation qualification, with no navigation authority."""
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 CLIPSegConfig, CLIPSegForImageSegmentation, CLIPSegProcessor
PROMPTS = ['sidewalk', 'road', 'crosswalk', 'building', 'wall', 'vegetation', 'stairs']
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)
root = Path('/assets')
descriptor = json.loads(Path('/adapter/model.json').read_text())
for name, expected in descriptor['files'].items():
assert sha(root / name) == expected, name
processor = CLIPSegProcessor.from_pretrained(root, local_files_only=True)
model = CLIPSegForImageSegmentation(CLIPSegConfig.from_pretrained(root, local_files_only=True))
state = torch.load(root / 'pytorch_model.bin', weights_only=True, map_location='cpu')
# Legacy Transformers saved these deterministic buffers; current versions
# regenerate them. Verify equality before removing only those extra keys.
for key in ('clip.text_model.embeddings.position_ids', 'clip.vision_model.embeddings.position_ids'):
if key in state and key not in model.state_dict():
assert torch.equal(state.pop(key), model.get_buffer(key)), key
model.load_state_dict(state, strict=True)
del state
model.cuda().eval()
rows = []
output = Path('/evidence')
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')
inputs = processor(text=PROMPTS, images=[image] * len(PROMPTS), padding=True, return_tensors='pt').to('cuda')
torch.cuda.synchronize()
begin = time.monotonic()
with torch.inference_mode():
logits = model(**inputs).logits
logits = torch.nn.functional.interpolate(logits[:,None], size=(image.height,image.width), mode='bilinear', align_corners=False)[:,0]
scores = logits.sigmoid().cpu().numpy()
torch.cuda.synchronize()
elapsed = time.monotonic() - begin
# Scores for separate prompts are diagnostic similarities, not calibrated probabilities.
labels = scores.argmax(axis=0)
known = scores.max(axis=0) >= .5
colors = np.zeros((*labels.shape,3), dtype=np.uint8)
for label,color in [(0,[20,220,170]),(1,[220,40,50]),(2,[240,200,20])]:
colors[(labels==label)&known] = color
Image.blend(image,Image.fromarray(colors),.45).save(output/(path.stem+'.jpg'))
np.savez_compressed(output/(path.stem+'.npz'),scores=scores.astype(np.float16),prompts=np.array(PROMPTS))
row=dict(source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),inference_seconds=elapsed,
fractions={prompt:float(((labels==i)&known).mean()) for i,prompt in enumerate(PROMPTS)},
max_scores={prompt:float(scores[i].max()) for i,prompt in enumerate(PROMPTS)})
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,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()
descriptor = json.loads((adapter / "model.json").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-clipseg-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=240, 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()