AGT / code /agt /eval /scorer.py
MRBSTUDIO's picture
Update the inference and evaluation code
2ad60ce verified
Raw History Blame Contribute Delete
5.8 kB
from __future__ import annotations
import json
from pathlib import Path
from agt.data.protocol import ClipProtocol
from agt.data.reader import open_reader
from agt.data.store import LabelsUnavailable
from .depth import DepthLabels, aggregate, frame_metrics, frame_reasons, native_cells_in_v
from .hole import HoleScorer
from .labels import MaskProvider, VisibilityProvider, source_of
from .method_dir import MethodDirectory, select_scored
from .output_grid import depth_to_scoring_grid, to_scoring_grid
from .regional import RegionScorer
from .regions import partition
from .rgb import RGBScorer
from .summary import METRICS, export, write_json
DEFAULTS = dict(protocol='partial', map_version='v2', source='waymo', scoring_mask='ground_truth',
visibility='gt_visibility_v2', boundary_width=3, min_pixels=49, depth_alpha_eps=1e-3, device='cuda',
clips=None)
def score_depth(labels, clip, output, positions, *, eps):
if labels is None or not labels.has_scene(clip['scene_id']):
return dict(status='no_gt_labels', rmse=None, absrel=None)
data = labels.read(clip['scene_id'], [clip['frame_indices'][p] for p in positions])
native_shape = data['native'].shape[1:]
if output is None:
pred, alpha, output_positions = None, None, []
else:
from agt.data.grid import ScoringGrid
pred, alpha = depth_to_scoring_grid(output['depth'], output.get('alpha'), ScoringGrid())
output_positions = output['positions']
frames = []
for i, p in enumerate(positions):
mask = data['eval_valid'][i]
reasons = frame_reasons(data['scan_time_offset_us'][i], native_cells_in_v(mask, native_shape))
if reasons or not mask.any():
frames.append(None)
continue
j = output_positions.index(p) if p in output_positions else None
frames.append(frame_metrics(None if j is None else pred[j], data['depth_z_m'][i], mask,
alpha=None if j is None or alpha is None else alpha[j], eps=eps))
return dict(status='ok', **aggregate(frames))
def score(config: dict) -> dict:
cfg = {**DEFAULTS, **config}
data_root, source, device = Path(cfg['data_root']), cfg['source'], cfg['device']
protocol = ClipProtocol.load(cfg['protocol'])
positions = protocol.frame_set_positions('interp')
regions_scorer = RegionScorer(device, min_pixels=cfg['min_pixels'])
rgb = RGBScorer(device)
hole = HoleScorer(regions_scorer)
inputs = Path(cfg['export'])
manifest = json.loads((inputs/'manifest.json').read_text())
split = cfg.get('split') or manifest['scoring_subset']['split']
reader = open_reader(data_root, split, protocol, map_version=cfg['map_version'], sources=[source], time_of_day='both')
canonical = {c['clip_id']: c for c in reader.clips()}
mask_provider = MaskProvider(data_root, cfg['scoring_mask'])
visibility = VisibilityProvider(data_root, cfg['visibility'])
labels = None
if (data_root/'labels/lidar_dggt_single_v2').is_dir():
labels = DepthLabels(data_root/'labels/lidar_dggt_single_v2', data_root/'labels/sky_v1', [source])
method = MethodDirectory(cfg['method'])
per_clip = []
for cid in cfg['clips'] or manifest['clips']:
if cid not in manifest['clips'] or cid not in canonical:
raise ValueError(f'clip {cid} is outside the export / the protocol clips of the data root')
clip = json.loads((inputs/cid/'clip.json').read_text()); selected = canonical[cid]
for key in ('frame_indices', 'roles', 'scene_id'):
if clip[key] != selected[key]:
raise ValueError(f'{cid}: export vs data-root clip {key} mismatch (export built from other data?)')
if source_of(clip) != source:
raise ValueError('clip/export source mismatch')
data = reader.load(selected, rgb=('clean',))
masks, _ = mask_provider.load(clip)
try:
visible, _ = visibility.load(clip)
except LabelsUnavailable:
visible = None
output = method.predict(selected)
prediction = to_scoring_grid(select_scored(output, len(clip['frame_indices']), positions), reader.grid)
gt = data['rgb_clean'][positions]
full = rgb.score(prediction, gt)
values = dict.fromkeys(METRICS)
values.update(full_psnr=full['rgb_psnr'], full_ssim=full['rgb_ssim'], full_lpips=full['rgb_lpips'])
status = 'visibility_unavailable'
if visible is not None:
status = 'ok'
regions = partition(masks[positions], visible[positions], width=cfg['boundary_width'])
observed = regions_scorer.region(prediction, gt, regions['observed'])
unobserved = regions_scorer.region(prediction, gt, regions['unobserved'], structural=False, perceptual=False)
holes = hole.score(prediction, gt, regions['unobserved'])
values.update(observed_psnr=observed['psnr'], observed_ssim=observed['ssim'], observed_lpips=observed['lpips'],
unobserved_psnr=unobserved['psnr'], unobserved_lpips=holes['lpips'],
unobserved_dists=holes['dists'])
if method.depth is not None:
depth = score_depth(labels, clip, method.predict_depth(clip), positions, eps=cfg['depth_alpha_eps'])
values.update(depth_absrel=depth['absrel'], depth_rmse=depth['rmse'])
per_clip.append(dict(source_id=source, scene_id=clip['scene_id'], clip_id=cid, status=status, values=values))
print(json.dumps(dict(scored_clip=cid)), flush=True)
reader.close()
out = Path(cfg['out'])
write_json(out/'config.json', {k: str(v) if isinstance(v, Path) else v for k, v in cfg.items()})
return export(per_clip, out)