"""Produce native-XYZ ON/OFF samples using a verified saved EMA teacher.""" from __future__ import annotations import argparse import dataclasses import json from pathlib import Path def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--teacher", type=Path, required=True) parser.add_argument("--input", type=Path, required=True) parser.add_argument("--labels", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--model-label", required=True) parser.add_argument("--device", default="cuda:0") parser.add_argument( "--context-grid", type=int, default=32, help="0 disables auxiliary grid queries" ) parser.add_argument("--camera", choices=("on", "off", "both"), default="both") args = parser.parse_args() if args.output.exists(): parser.error("The prediction file already exists") if args.context_grid < 0: parser.error("--context-grid must be nonnegative") import numpy as np import torch from evaluation.decoder_kv_cache import cache_decoder_projections from evaluation.scale4d import SCALE4D from evaluation.scale4d_inputs import npz_clip from evaluation.ucpe_inputs import ClipLabels from evaluation.ucpe_scores import score_tracks receipt = json.loads((args.teacher / "teacher.json").read_text()) if receipt.get("weight_role") != "ema_teacher": raise ValueError("The export does not identify saved EMA teacher weights") model = SCALE4D(args.teacher, device=args.device) if model.info.step != receipt["checkpoint_step"]: raise ValueError("Loaded teacher step differs from the export receipt") clip = npz_clip(args.input) count = len(clip.query_times) height, width = clip.rgbs.shape[-2:] with np.load(args.labels, allow_pickle=False) as data: labels = ClipLabels( data["gt_tracks_target_camera"], data["visibility"], data.get("visibility_known"), ) extended = None if args.context_grid: ys, xs = torch.meshgrid( torch.linspace(0.5, height - 1.5, args.context_grid), torch.linspace(0.5, width - 1.5, args.context_grid), indexing="ij", ) uv = torch.stack([xs.flatten(), ys.flatten()], -1) extended = dataclasses.replace( clip, query_uv=torch.cat([clip.query_uv, uv]), query_times=torch.cat( [clip.query_times, torch.zeros(len(uv), dtype=torch.long)] ), query_views=torch.cat( [clip.query_views, torch.zeros(len(uv), dtype=torch.long)] ), ) xy = uv.round().long() colors = clip.rgbs[0, 0, :, xy[:, 1], xy[:, 0]].T.numpy() mask = ( np.arange(clip.rgbs.shape[1])[:, None] > clip.query_times.numpy()[None] if clip.metadata.get("query_policy") in ("first_visible_left", "first_visible_anchor") else None ) predictions, context, context_valid, differences, scores = [], [], [], [], {} camera_modes = ("on", "off") if args.camera == "both" else (args.camera,) for camera in camera_modes: with cache_decoder_projections(model.evaluator.model.decoder): result = model.predict_clip(clip, views=3, camera=camera) predictions.append(result) scores[camera] = score_tracks( labels, result.xyz.numpy(), result.visibility.numpy(), evaluation_mask=mask )["metric"] if extended is None: continue with cache_decoder_projections(model.evaluator.model.decoder): dense = model.predict_clip(extended, views=3, camera=camera) difference = float(torch.max(torch.abs(dense.xyz[:, :count] - result.xyz))) if difference > 0.005: raise ValueError( "Context inference changed sparse predictions by over 5 mm" ) xyz = dense.xyz[:, count:].numpy() valid = ( np.isfinite(xyz).all(-1) & (xyz[..., 2] > 0) & (np.abs(xyz).max(-1) < 32) ) context.append(xyz) context_valid.append(valid) differences.append(difference) metadata = { "arm": args.model_label, "weight_role": "ema_teacher", "checkpoint_step": receipt["checkpoint_step"], "teacher_state_sha256": receipt["teacher_state_sha256"], "position_source": "xyz", "query_count": count, "query_fingerprint": clip.metadata.get("query_fingerprint"), "scores": scores, "context_grid": args.context_grid, "context_replay_max_difference_m": differences, } args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open("xb") as handle: arrays = { "positions": np.stack([p.xyz.numpy() for p in predictions]), "uv": np.stack([p.uv.numpy() for p in predictions]), "visibility": np.stack([p.visibility.numpy() for p in predictions]), "confidence": np.stack([p.confidence.numpy() for p in predictions]), "camera_modes": np.array(camera_modes), "metadata_json": json.dumps(metadata), } if context: arrays.update( dense_positions=np.stack(context), dense_valid=np.stack(context_valid), dense_colors=colors, ) np.savez_compressed(handle, **arrays) print(json.dumps(metadata, indent=2)) if __name__ == "__main__": main()