Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"repository": "facebook/mask2former-swin-large-mapillary-vistas-semantic",
|
||||
"revision": "2cc022513f0012ff47d4438516284fd0946a196a",
|
||||
"asset_directory": "mask2former-mapillary",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"config.json": "b40bec8d82de3b53ef967dce0496c37de520b69466f1a8d2f6c035700cbae9f3",
|
||||
"preprocessor_config.json": "22ef0608c7add19c5e9a64f8eeba95b7d3d1237ef20bf14efead9d8bc671da9f",
|
||||
"README.md": "b534d1a4be6fd8f61da29dde0887ccdffb18f866a1ab88da381fb585c9ba60c7",
|
||||
"pytorch_model.bin": "8120d77b194b34527b5937a576c36291ae7e76157f57a22433480c19d71e1551"
|
||||
}
|
||||
}
|
||||
@@ -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,70 @@
|
||||
"""Bounded recorded-image qualification. Produces no navigation command."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--context", action="store_true")
|
||||
args = parser.parse_args()
|
||||
descriptor = json.loads(Path("/adapter/model.json").read_text())
|
||||
for name, expected in descriptor["files"].items():
|
||||
digest = hashlib.sha256()
|
||||
with (Path("/assets") / name).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
assert digest.hexdigest() == expected, name
|
||||
output = Path("/evidence")
|
||||
torch.set_num_threads(3)
|
||||
processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True)
|
||||
model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval()
|
||||
rows = []
|
||||
for path in sorted(Path("/inputs").glob("*-crop.jpg")):
|
||||
original = Image.open(path).convert("RGB")
|
||||
for crop in ((False,) if args.context else (True, False)):
|
||||
image = original.crop((100, 0, 700, 600)) if crop else original
|
||||
for size in ((1024, 1536, 2048) if args.context else (384, 768)):
|
||||
shape = ({"height": round(size * image.height / image.width), "width": size}
|
||||
if args.context else {"height": size, "width": size})
|
||||
inputs = processor(images=image, return_tensors="pt", size=shape).to("cuda")
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
torch.cuda.synchronize()
|
||||
begin = time.monotonic()
|
||||
with torch.inference_mode():
|
||||
prediction = model(**inputs)
|
||||
labels = processor.post_process_semantic_segmentation(
|
||||
prediction, target_sizes=[(image.height, image.width)]
|
||||
)[0].cpu().numpy().astype(np.uint8)
|
||||
torch.cuda.synchronize()
|
||||
elapsed = time.monotonic() - begin
|
||||
key = f"{path.stem}-{'crop' if crop else 'full'}-{size}"
|
||||
Image.fromarray(labels).save(output / (key + ".labels.png"))
|
||||
# Only visualization: pedestrian area/sidewalk cyan, road red,
|
||||
# potential crossing yellow. These colors grant no permissions.
|
||||
colors = np.zeros((*labels.shape, 3), dtype=np.uint8)
|
||||
colors[np.isin(labels, (11, 15))] = [20, 220, 170]
|
||||
colors[labels == 13] = [220, 40, 50]
|
||||
colors[np.isin(labels, (8, 23))] = [240, 200, 20]
|
||||
Image.blend(image, Image.fromarray(colors), .45).save(output / (key + ".jpg"))
|
||||
ids, counts = np.unique(labels, return_counts=True)
|
||||
rows.append(dict(case=key, inference_seconds=elapsed,
|
||||
input_shape=list(inputs["pixel_values"].shape),
|
||||
gpu_peak_bytes=torch.cuda.max_memory_allocated(),
|
||||
pedestrian_fraction=float(np.isin(labels, (11, 15)).mean()),
|
||||
road_fraction=float((labels == 13).mean()),
|
||||
classes={model.config.id2label[int(i)]: int(n) for i, n in zip(ids, counts)}))
|
||||
(output / "results.json").write_text(json.dumps(rows, indent=2))
|
||||
print(json.dumps(rows[-1]), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""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("--context", action="store_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-mapillary-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",
|
||||
*(["--context"] if args.context else []),
|
||||
], 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()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Pinned urban surface inference; potential crossings grant no driving authority."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
|
||||
def main():
|
||||
descriptor = json.loads(Path(__file__).with_name("model.json").read_text())
|
||||
for name, expected in descriptor["files"].items():
|
||||
digest = hashlib.sha256()
|
||||
with (Path("/assets") / name).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != expected:
|
||||
raise RuntimeError("Mapillary asset identity changed: " + name)
|
||||
processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True)
|
||||
model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval()
|
||||
torch.set_num_threads(3)
|
||||
|
||||
def infer(rgb):
|
||||
# Preserve the existing central-square pixel geometry. 768 is an
|
||||
# explicitly qualified processor override, not a checkpoint default.
|
||||
image = Image.fromarray(rgb).crop((100, 0, 700, 600))
|
||||
inputs = processor(images=image, return_tensors="pt", size={"height": 768, "width": 768}).to("cuda")
|
||||
with torch.inference_mode():
|
||||
output = model(**inputs)
|
||||
masks = torch.nn.functional.interpolate(output.masks_queries_logits,
|
||||
size=(512, 512), mode="bilinear", align_corners=False).sigmoid()
|
||||
classes = output.class_queries_logits.softmax(-1)[..., :-1]
|
||||
scores = torch.einsum("bqc,bqhw->bchw", classes, masks)
|
||||
score, labels = scores.max(1)
|
||||
# Query-aggregated scores are not calibrated class probabilities.
|
||||
# Require both absolute evidence and dominance over other classes.
|
||||
known = (score >= .55) & (score / scores.sum(1).clamp_min(1e-8) >= .55)
|
||||
labels = labels[0].cpu().numpy().astype(np.uint8)
|
||||
known = known[0].cpu().numpy()
|
||||
candidate = np.isin(labels, (7, 8, 9, 10, 11, 13, 14, 15, 23)) & known
|
||||
return labels.tobytes() + candidate.astype(np.uint8).tobytes() + known.astype(np.uint8).tobytes()
|
||||
|
||||
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,
|
||||
b'{"model":"mask2former-mapillary65"}')
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/infer" or self.headers.get("Content-Length") != "1440000":
|
||||
self.reply(400, b"Expected 800x600 raw 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"Surface inference failed")
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
HTTPServer(("0.0.0.0", 8010), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user