File size: 5,593 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | """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()
|