Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
74 lines
4.3 KiB
Python
74 lines
4.3 KiB
Python
"""Keep every task-class score, never a per-frame winner-only ground mask."""
|
|
import time
|
|
from pathlib import Path
|
|
import numpy as np
|
|
import torch
|
|
from PIL import Image
|
|
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation, SegformerForSemanticSegmentation
|
|
from mv_math import GROUPS, group_matrix
|
|
from mv_io import RUN, MODEL, config, read, write, digest, record, guard
|
|
|
|
start = time.monotonic()
|
|
cfg = config()
|
|
asset = cfg['models'][MODEL]
|
|
model_dir = Path('/models') / MODEL
|
|
for name, expected in asset['files'].items():
|
|
assert digest(model_dir / name) == expected, name
|
|
processor = AutoImageProcessor.from_pretrained(model_dir, local_files_only=True)
|
|
cls = Mask2FormerForUniversalSegmentation if MODEL == 'mapillary' else SegformerForSemanticSegmentation
|
|
model = cls.from_pretrained(model_dir, local_files_only=True).cuda().eval()
|
|
matrix = torch.tensor(group_matrix(MODEL, model.config.num_labels), device='cuda')
|
|
plan = read(RUN / 'cameras.json')
|
|
folder = RUN / MODEL / 'scores'
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
completed = 0
|
|
signature = dict(model=asset, cameras=digest(RUN / 'cameras.json'), implementation=digest(__file__),
|
|
grouping=digest(Path(__file__).with_name('mv_math.py')), input_size=[800, 600],
|
|
score_size=[400, 300], precision='autocast-bfloat16; aggregation float32')
|
|
for station in plan['stations']:
|
|
guard()
|
|
for spec in station['views']:
|
|
name = spec['id']
|
|
image_path = RUN / 'views' / (name + '.png')
|
|
receipt = folder / (name + '.json')
|
|
inputs = dict(signature, rgb_sha256=digest(image_path))
|
|
target = folder / (name + '.npz')
|
|
if receipt.exists():
|
|
cached = read(receipt)
|
|
if cached['inputs'] != inputs or digest(target) != cached['sha256']:
|
|
raise ValueError('Stale semantic cache')
|
|
completed += 1
|
|
continue
|
|
im = Image.open(image_path).convert('RGB')
|
|
tensors = processor(images=im, return_tensors='pt', size={'height': 600, 'width': 800}).to('cuda')
|
|
padded_size = tuple(tensors['pixel_values'].shape[-2:])
|
|
if not (600 <= padded_size[0] < 632 and 800 <= padded_size[1] < 832):
|
|
raise ValueError('Unexpected processor geometry: ' + str(padded_size))
|
|
if completed == 0:
|
|
record(dict(stage='processor', model=MODEL, input_size=list(padded_size), unpadded_size=[600,800]))
|
|
with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16):
|
|
result = model(**tensors)
|
|
if MODEL == 'mapillary':
|
|
# Upstream semantic query aggregation, with no hard class choice.
|
|
classes = result.class_queries_logits.float().softmax(-1)[..., :-1]
|
|
masks = torch.nn.functional.interpolate(result.masks_queries_logits.float(), size=padded_size,
|
|
mode='bilinear', align_corners=False)[:, :, :600, :800]
|
|
masks = torch.nn.functional.interpolate(masks, size=(300, 400), mode='bilinear', align_corners=False).sigmoid()
|
|
all_scores = torch.einsum('bqc,bqhw->bchw', classes, masks)[0]
|
|
else:
|
|
logits = torch.nn.functional.interpolate(result.logits.float(), size=padded_size,
|
|
mode='bilinear', align_corners=False)[:, :, :600, :800]
|
|
all_scores = torch.nn.functional.interpolate(logits, size=(300, 400), mode='bilinear', align_corners=False)[0].softmax(0)
|
|
groups = torch.einsum('gc,chw->ghw', matrix, all_scores)
|
|
groups /= groups.sum(0).clamp_min(1e-8)
|
|
scores = groups.cpu().numpy().astype(np.float16)
|
|
assert np.isfinite(scores).all() and np.max(abs(scores.astype(np.float32).sum(0) - 1)) < .002
|
|
np.savez_compressed(target, scores=scores)
|
|
write(receipt, dict(inputs=inputs, sha256=digest(target), groups=GROUPS, calibrated=False))
|
|
completed += 1
|
|
del tensors, result, all_scores, groups
|
|
record(dict(stage='infer', model=MODEL, completed=completed, total=plan['view_count'], elapsed_s=time.monotonic() - start))
|
|
write(RUN / MODEL / 'inference-summary.json', dict(model=MODEL, views=completed, inputs=signature,
|
|
seconds=time.monotonic() - start, groups=GROUPS,
|
|
scores='normalized task-class mass; not calibrated probabilities'))
|