Files
NODEDC_MISSION_CORE/simulation/ai-polygon/sidewalk-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

91 lines
4.6 KiB
Python

"""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()