"""Offline detector + tracker evaluation on whole SimLingo routes, against the oracle object bank. Runs models/detector.py frame by frame (4 Hz logs, consecutive frames as the two-frame input) and team_code/tracker.py on the ground-truth ego pose, then compares the tracker's rows with the oracle bank rows the stage-3 model was trained on (object_bank/.../objects.npz) in the tracker acceptance terms: recall of visible bank objects per range bin, false tracks per second, position / speed / heading errors and identity switches. Optionally writes the tracker rows per route in the bank layout (--write-banks) for stage-3 fine-tuning on real perception; relation labels move from the oracle bank to the matched tracks, unmatched tracks are labelled ignore. Usage: python scripts/eval_tracker_offline.py --detector outputs/detector//last.pt --out [--split train|val|all] [--sample-routes N] [--shard K/N] [--write-banks [--bank-folder F]] [--save-detections | --reuse-detections] (cache detections once, re-run the tracker on CPU) """ import argparse import json import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np import torch from scipy.optimize import linear_sum_assignment sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from dataloader.detection_data import CAMERA_X, DetectionDataset, ego_motion, load_image, route_fold # noqa: E402 from dataloader.detection_labels import EGO_X, EGO_Y, EGO_YAW, OBJ_X, OBJ_Y # noqa: E402 from dataloader.object_bank import ( # noqa: E402 RAW_CLASS, RAW_DIM, RAW_SPEED, RAW_VISIBLE, RAW_X, RAW_Y, RAW_YAW, RELATION_IGNORE, RELATION_PAD, ) from models.detector import decode, load_detector # noqa: E402 from team_code.tracker import Tracker, TrackerConfig, detections_to_world # noqa: E402 FRAME_DT = 0.25 RANGE_BINS = ((0, 10), (10, 20), (20, 30), (30, 40), (40, 50)) def run_route(model, route_dir, objects, count, ego, device, score_threshold, tracker_cfg, batch=32, pool=None): """Detector outputs for every frame (pairs f-1, f), then the tracker over the sequence.""" dets = detect_route(model, route_dir, len(count), ego, device, score_threshold, batch, pool) return track_route(dets, ego, score_threshold, tracker_cfg) @torch.no_grad() def detect_route(model, route_dir, n, ego, device, score_threshold, batch=32, pool=None): """Decoded detections (scores >= min(score_threshold, 0.2)) per frame; None for frame 0.""" dets = [None] * n for start in range(1, n, batch): frames = list(range(start, min(n, start + batch))) paths = [f"{route_dir}/rgb/{f:04d}.jpg" for f in range(start - 1, frames[-1] + 1)] window = torch.stack(list(pool.map(load_image, paths)) if pool else [load_image(p) for p in paths]) window = window.to(device) img, prev = window[1:], window[:-1] motion = torch.stack([torch.from_numpy(ego_motion(ego[f - 1], ego[f])) for f in frames]).to(device) with torch.autocast("cuda", dtype=torch.bfloat16): out, _ = model(img, prev, motion) for f, d in zip(frames, decode(out, score_threshold=min(score_threshold, 0.2))): dets[f] = {k: v.float().cpu().numpy() for k, v in d.items()} return dets @torch.no_grad() def detect_routes_stream(model, route_dirs, lengths, egos, device, score_threshold, pool=None): """Streaming detector (models/stream_petr.py) over several routes in lockstep: one image per route per step, memory reset at the start; shorter routes are padded with their last frame. Returns per-route detection lists (frame 0 included, as the detector needs no earlier frame).""" from models.stream_petr import decode_stream b, n_max = len(route_dirs), max(lengths) dets = [[None] * n for n in lengths] model.reset_memory() for f in range(n_max): fs = [min(f, n - 1) for n in lengths] paths = [f"{d}/rgb/{fi:04d}.jpg" for d, fi in zip(route_dirs, fs)] images = torch.stack(list(pool.map(load_image, paths)) if pool else [load_image(p) for p in paths]).to(device) pose = torch.tensor(np.stack([e[fi, [EGO_X, EGO_Y, EGO_YAW]] for e, fi in zip(egos, fs)]), dtype=torch.float32, device=device) time_t = torch.tensor([fi * FRAME_DT for fi in fs], dtype=torch.float32, device=device) with torch.autocast("cuda", dtype=torch.bfloat16): out = model(images, pose, time_t) for i, d in enumerate(decode_stream(out, score_threshold=min(score_threshold, 0.2))): if f < lengths[i]: dets[i][f] = {k: v.float().cpu().numpy() for k, v in d.items() if k in DET_KEYS_ALL} model.reset_memory() return dets def load_any_detector(path, device): """(model, is_stream) for a train_detector.py or train_stream_petr.py checkpoint.""" args = torch.load(path, map_location="cpu", weights_only=False).get("args", {}) if "num_queries" in args: from models.stream_petr import load_stream_petr return load_stream_petr(path, device), True return load_detector(path, device), False DET_KEYS = ("x", "y", "z", "yaw", "speed", "vx", "vy", "half_l", "half_w", "half_h", "cls", "score", "depth_sigma") DET_KEYS_ALL = (*DET_KEYS, "velocity_sigma") def save_detections(path, dets): """Per-frame detections (detect_route output) -> one flat npz so the tracker can be re-run without the model.""" frames = [f for f, d in enumerate(dets) if d is not None] arrays = {k: np.concatenate([dets[f][k] for f in frames]) if frames else np.zeros(0) for k in DET_KEYS} arrays["velocity_sigma"] = (np.concatenate([dets[f]["velocity_sigma"] for f in frames]) if frames else np.zeros((0, 2))) arrays["frame"] = np.concatenate([np.full(len(dets[f]["score"]), f, dtype=np.int32) for f in frames]) \ if frames else np.zeros(0, dtype=np.int32) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp.npz") np.savez(tmp, n_frames=np.int32(len(dets)), **{k: v.astype(np.float32) if k != "frame" else v for k, v in arrays.items()}) tmp.rename(path) def load_detections(path): with np.load(path) as z: n, frame = int(z["n_frames"]), z["frame"] data = {k: z[k] for k in (*DET_KEYS, "velocity_sigma")} dets = [None] * n for f in range(n): sel = frame == f if f == 0 and not sel.any(): continue # two-frame detector: no detections on a route's first frame dets[f] = {k: v[sel] for k, v in data.items()} return dets def track_route(dets, ego, score_threshold, tracker_cfg): """Tracker rows over a route from per-frame detections (detect_route).""" n = len(dets) tracker = Tracker(tracker_cfg) rows = np.zeros((n, tracker_cfg.max_objects, RAW_DIM), dtype=np.float32) ids = np.zeros((n, tracker_cfg.max_objects), dtype=np.int64) counts = np.zeros(n, dtype=np.int16) for f in range(n): ego_xy, ego_yaw = ego[f, [EGO_X, EGO_Y]].astype(np.float64), float(ego[f, EGO_YAW]) world = [] if dets[f] is not None: keep = dets[f]["score"] >= score_threshold world = detections_to_world({k: v[keep] for k, v in dets[f].items()}, ego_xy, ego_yaw) rows[f], ids[f], counts[f] = tracker.step(f * FRAME_DT, world, ego_xy, ego_yaw) return rows, ids, counts def match_rows(g_xy, p_xy): """Bank row index -> tracker row index (-1 if unmatched), Hungarian within 1.5 m + 5% of range.""" assigned = np.full(len(g_xy), -1) if len(g_xy) and len(p_xy): g_rng = np.hypot(g_xy[:, 0] - CAMERA_X, g_xy[:, 1]) d = np.linalg.norm(g_xy[:, None] - p_xy[None], axis=-1) cost = np.where(d <= (1.5 + 0.05 * g_rng)[:, None], d, 1e6) r, c = linear_sum_assignment(cost) keep = cost[r, c] < 1e5 assigned[r[keep]] = c[keep] return assigned def transfer_relations(bank_raw, bank_rel, bank_count, trk_raw, trk_count): """Relation labels for tracker rows: the label of the matched bank object, ignore for unmatched tracks.""" rel = np.full(trk_raw.shape[:2], RELATION_PAD, dtype=np.int8) for f in range(len(trk_count)): rel[f, :trk_count[f]] = RELATION_IGNORE g = bank_raw[f, :bank_count[f]].astype(np.float64) p = trk_raw[f, :trk_count[f]].astype(np.float64) assigned = match_rows(g[:, [RAW_X, RAW_Y]], p[:, [RAW_X, RAW_Y]]) for i in np.nonzero(assigned >= 0)[0]: rel[f, assigned[i]] = bank_rel[f, i] return rel class TrackMetrics: """Tracker rows vs oracle bank rows, frame by frame.""" def __init__(self): self.gt = [] # range, class, visible, matched, pos err, speed gt, speed err, yaw err self.false_tracks = 0 self.frames = 0 self.id_switches = 0 self.matched_pairs = 0 def add_route(self, bank_raw, bank_ids, bank_count, trk_raw, trk_count, trk_ids, labels, label_count): last_track_of = {} for f in range(len(bank_count)): self.frames += 1 g = bank_raw[f, :bank_count[f]].astype(np.float64) p = trk_raw[f, :trk_count[f]].astype(np.float64) g_xy, p_xy = g[:, [RAW_X, RAW_Y]], p[:, [RAW_X, RAW_Y]] g_rng = np.hypot(g_xy[:, 0] - CAMERA_X, g_xy[:, 1]) assigned = match_rows(g_xy, p_xy) for i in range(len(g)): j = assigned[i] if j >= 0: gv = g[i, RAW_SPEED] * np.array((np.cos(g[i, RAW_YAW]), np.sin(g[i, RAW_YAW]))) pv = p[j, RAW_SPEED] * np.array((np.cos(p[j, RAW_YAW]), np.sin(p[j, RAW_YAW]))) yaw_err = abs(np.angle(np.exp(1j * (p[j, RAW_YAW] - g[i, RAW_YAW])))) self.gt.append((g_rng[i], g[i, RAW_CLASS], g[i, RAW_VISIBLE], 1.0, np.linalg.norm(g_xy[i] - p_xy[j]), g[i, RAW_SPEED], np.linalg.norm(gv - pv), yaw_err)) gid, tid = int(bank_ids[f, i]), int(trk_ids[f, j]) if gid in last_track_of and last_track_of[gid] != tid: self.id_switches += 1 last_track_of[gid] = tid self.matched_pairs += 1 else: self.gt.append((g_rng[i], g[i, RAW_CLASS], g[i, RAW_VISIBLE], 0.0, np.nan, g[i, RAW_SPEED], np.nan, np.nan)) # false track: no labelled box at all (visible or not) near it lab = labels[f, :label_count[f]] l_xy = lab[:, [OBJ_X, OBJ_Y]].astype(np.float64) for j in range(len(p)): prng = np.hypot(p_xy[j, 0] - CAMERA_X, p_xy[j, 1]) if prng > 50.0 or j in assigned: continue near_label = len(l_xy) and np.min(np.linalg.norm(l_xy - p_xy[j], axis=-1)) <= 1.5 + 0.05 * prng near_bank = len(g_xy) and np.min(np.linalg.norm(g_xy - p_xy[j], axis=-1)) <= 1.5 + 0.05 * prng if not near_label and not near_bank: self.false_tracks += 1 def summary(self): gt = np.asarray(self.gt, dtype=np.float64).reshape(-1, 8) out = dict(frames=self.frames, seconds=self.frames * FRAME_DT, false_tracks_per_s=self.false_tracks / max(self.frames * FRAME_DT, 1e-6), id_switches_per_100_matches=100.0 * self.id_switches / max(self.matched_pairs, 1)) for c, name in enumerate(("car", "walker", "static")): rows = {} for lo, hi in RANGE_BINS: sel = (gt[:, 1] == c) & (gt[:, 0] >= lo) & (gt[:, 0] < hi) vis, mem = sel & (gt[:, 2] > 0.5), sel & (gt[:, 2] <= 0.5) m = vis & (gt[:, 3] > 0) rows[f"{lo}-{hi}"] = dict( n_visible=int(vis.sum()), recall_visible=float(gt[vis, 3].mean()) if vis.any() else None, recall_memory=float(gt[mem, 3].mean()) if mem.any() else None, pos_err_med=float(np.median(gt[m, 4])) if m.any() else None, pos_err_p90=float(np.percentile(gt[m, 4], 90)) if m.any() else None, vel_err_med=float(np.median(gt[m, 6])) if m.any() else None) out[name] = rows cars = gt[(gt[:, 1] == 0) & (gt[:, 2] > 0.5) & (gt[:, 3] > 0) & (gt[:, 0] < 50)] speed = {} for lo, hi in ((0, 0.5), (0.5, 5), (5, 10), (10, 20)): s = cars[(cars[:, 5] >= lo) & (cars[:, 5] < hi)] if len(s): speed[f"{lo}-{hi}"] = dict(n=len(s), vel_err_med=float(np.median(s[:, 6])), vel_err_rms=float(np.sqrt(np.mean(s[:, 6] ** 2))), target_sigma=0.3 + 0.1 * 0.5 * (lo + hi), yaw_err_med_deg=float(np.degrees(np.median(s[:, 7])))) out["car_velocity_by_speed"] = speed return out def format_summary(s): lines = [f"{s['frames']} frames ({s['seconds']:.0f} s) false tracks/s {s['false_tracks_per_s']:.3f} " f"id switches / 100 matches {s['id_switches_per_100_matches']:.2f}"] f = lambda v, p=3: f"{v:6.{p}f}" if v is not None else " -" # noqa: E731 for name in ("car", "walker", "static"): lines.append(f"{name:7s} range n_vis rec_vis rec_mem err_med err_p90 vel_err") for key, r in s[name].items(): lines.append(f" {key:5s} {r['n_visible']:6d} {f(r['recall_visible'])} {f(r['recall_memory'])} " f"{f(r['pos_err_med'], 2)} {f(r['pos_err_p90'], 2)} {f(r['vel_err_med'], 2)}") for key, r in s["car_velocity_by_speed"].items(): lines.append(f"car speed {key:7s} n={r['n']:6d} vel_err med {r['vel_err_med']:.2f} rms {r['vel_err_rms']:.2f} " f"(target sigma {r['target_sigma']:.2f}) yaw_err med {r['yaw_err_med_deg']:.1f} deg") return "\n".join(lines) def main(): ap = argparse.ArgumentParser() ap.add_argument("--detector", required=True) ap.add_argument("--out", required=True) ap.add_argument("--split", default="val", help="train | val | all") ap.add_argument("--max-routes", type=int, default=0) ap.add_argument("--sample-routes", type=int, default=0, help="random subset of this many routes (seeded)") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--shard", default="0/1", help="K/N: process every N-th route starting at K") ap.add_argument("--fold", default=None, help="K/N: only routes of cross-fitting fold K (pair with a detector trained with " "--holdout-fold K/N)") ap.add_argument("--score-threshold", type=float, default=0.3) ap.add_argument("--max-coast-s", type=float, default=2.0) ap.add_argument("--write-banks", action="store_true") ap.add_argument("--bank-folder", default="tracker_bank") ap.add_argument("--skip-existing", action="store_true", help="skip routes whose bank file already exists") ap.add_argument("--decode-threads", type=int, default=8) ap.add_argument("--stream-batch", type=int, default=8, help="routes run in lockstep by the streaming detector") ap.add_argument("--detections-folder", default="tracker_dets") ap.add_argument("--save-detections", action="store_true", help="cache the per-frame detections next to the banks (//dets.npz)") ap.add_argument("--reuse-detections", action="store_true", help="tracker-only run from cached detections (CPU); routes without a cache are skipped") args = ap.parse_args() device = torch.device("cuda") if not args.reuse_detections else None shard, num_shards = (int(v) for v in args.shard.split("/")) out = Path(args.out) / (f"shard_{shard}_of_{num_shards}" if num_shards > 1 else "") out.mkdir(parents=True, exist_ok=True) splits = ("train", "val") if args.split == "all" else (args.split,) datasets = [DetectionDataset(split=s) for s in splits] data_root = datasets[0].data_root routes = [r for d in datasets for r in d.routes] if args.sample_routes: pick = np.random.default_rng(args.seed).choice(len(routes), size=min(args.sample_routes, len(routes)), replace=False) routes = [routes[i] for i in sorted(pick)] if args.fold: fold, num_folds = (int(v) for v in args.fold.split("/")) routes = [r for r in routes if route_fold(str(Path(r[0]).relative_to(data_root / "data")), num_folds) == fold] routes = routes[: args.max_routes] if args.max_routes else routes routes = routes[shard::num_shards] model, is_stream = load_any_detector(args.detector, device) if not args.reuse_detections else (None, False) cfg = TrackerConfig(max_coast_s=args.max_coast_s) metrics = TrackMetrics() pool = ThreadPoolExecutor(args.decode_threads) if args.decode_threads > 1 else None t0 = time.time() missing_cache = 0 pending = [] # streaming detector: (index, route_dir, n, ego) of routes waiting for a lockstep batch stream_dets = {} def flush_pending(): if pending: out_dets = detect_routes_stream(model, [p[1] for p in pending], [p[2] for p in pending], [p[3] for p in pending], device, args.score_threshold, pool) stream_dets.update({p[0]: d for p, d in zip(pending, out_dets)}) pending.clear() for i, (route_dir, label_file) in enumerate(routes): rel = Path(route_dir).relative_to(data_root / "data") bank_file = data_root / "object_bank" / rel / "objects.npz" dst = data_root / args.bank_folder / rel / "objects.npz" det_file = data_root / args.detections_folder / rel / "dets.npz" if not bank_file.exists() or (args.skip_existing and dst.exists()): continue if args.reuse_detections and not det_file.exists(): missing_cache += 1 continue with np.load(label_file) as z: labels, label_count, ego = z["objects"], z["count"], z["ego"] with np.load(bank_file) as z: bank_raw, bank_ids, bank_rel, bank_count = z["raw"], z["ids"], z["relation"], z["count"] if args.reuse_detections: dets = load_detections(det_file) elif is_stream: # detections for this route come from the lockstep batch it belongs to (routes are processed # in order, so the batch is flushed as soon as this route's turn comes) if i not in stream_dets: j = i while j < len(routes) and len(pending) < args.stream_batch: rd, lf = routes[j] rj = Path(rd).relative_to(data_root / "data") bj, dj = data_root / "object_bank" / rj / "objects.npz", data_root / args.bank_folder / rj / "objects.npz" if bj.exists() and not (args.skip_existing and dj.exists()): with np.load(lf) as z: ej, nj = z["ego"], len(z["count"]) pending.append((j, rd, nj, ej)) j += 1 flush_pending() dets = stream_dets.pop(i) if args.save_detections: save_detections(det_file, dets) else: dets = detect_route(model, route_dir, len(label_count), ego, device, args.score_threshold, pool=pool) if args.save_detections: save_detections(det_file, dets) rows, ids, counts = track_route(dets, ego, args.score_threshold, cfg) metrics.add_route(bank_raw, bank_ids, bank_count, rows, counts, ids, labels, label_count) if args.write_banks: relation = transfer_relations(bank_raw, bank_rel, bank_count, rows, counts) dst.parent.mkdir(parents=True, exist_ok=True) tmp = dst.with_suffix(".tmp.npz") np.savez(tmp, raw=rows.astype(np.float16), ids=ids.astype(np.int32), relation=relation, count=counts, frame_dt=np.float32(FRAME_DT), detector=np.array(str(args.detector))) tmp.rename(dst) if (i + 1) % 20 == 0 or i + 1 == len(routes): print(f"[{i + 1}/{len(routes)}] {time.time() - t0:.0f}s", flush=True) if missing_cache: print(f"WARNING: {missing_cache} routes skipped, no cached detections", flush=True) summary = metrics.summary() summary["args"] = vars(args) (out / "tracker_metrics.json").write_text(json.dumps(summary, indent=1)) text = format_summary(summary) (out / "tracker_metrics.txt").write_text(text + "\n") print(text) if __name__ == "__main__": main()