File size: 12,992 Bytes
e91e989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""D21 task-level gates of a serve profile: a ``run_public_frames.py --stream`` output directory scored against the
stored CPU fp32 goldens of the same frames (CPU only; development tool of the workspace: needs the research goldens,
which never ship).

    python code/scripts/task_gates.py <candidate_dir> [--accurate <accurate_dir>] [--json out.json]

PLAN.md D21 (user decision 2026-10-19, METEOR): a reduced-precision ``fast`` profile is judged by TASK-LEVEL gates
against the CPU fp32 reference on the 38 public frames + the in-domain valday frames. Gates (fixed here, never
tuned; the frozen ``.gates.json`` files are not touched):

- 3D boxes: recall and precision >= 0.95, pooled over each split (strict matching: same class, BEV centre within
  0.5 m, greedy by score: the frozen e2e gate's radius; 1.0 m, compare_tt's radius, is reported);
- planned path: worst deviation <= 0.3 m (max waypoint distance between the reference's selected path and the
  candidate's path of the same mode, over every frame);
- plan mode agreement >= 0.95 and traffic-light agreement >= 0.95 (fraction of frames);
- lane / BEV-seg pixel agreement >= 0.98 on every frame (the raw lane argmax);
- depth / seg2d: OPT_PLAN A2's conservative reading gates them at >= 0.98 on every frame (reported as their own
  verdict: ``conservative``; D21 itself does not name them);
- 2D boxes (information only, OPT2 P1: D21 does not gate them): recall / precision of the per-camera 2D detections,
  pooled (same class, IoU >= 0.5, greedy by score);
- health checks (upstream INT8 lessons): the stationary head's health equal to the reference on every frame, the
  seg2d non-background fraction within 0.02 of the reference, no frozen output (the candidate's ego paths and hm
  differ between consecutive frames whenever the reference's do).

Splits: ``tune`` = PandaSet 019 + nuScenes 0103 + valday f010-f070; ``heldout`` = PandaSet 090 + valday f090-f130
(never used to choose a precision map; the gates apply to both). With ``--accurate`` (a run of the ``accurate``
profile with ``--stream``), the live-stream outputs (fused lane map, selected mode / path after hysteresis) of the
two profiles are compared frame by frame (reported: the drift of the host temporal state, StreamPETR R4.2).
"""
from __future__ import annotations

import argparse
import glob
import json
import math
import os
import sys
from pathlib import Path
from typing import Any, Dict, List

import numpy as np

ROOT = Path(os.environ.get("TT_MODELS_ROOT", "/home/ubuntu/experiments/tt-models"))
GOLDEN = ROOT / "research" / "meteor" / "public_data" / "golden"
SETS = ("ps019", "ps090", "ns0103", "meteor_valday")
HELDOUT = {"ps090": None, "meteor_valday": {90, 110, 130}}      # set -> frames (None: every frame)
GATES = {"det3d.recall": (0.95, "min"), "det3d.precision": (0.95, "min"), "ego.path_dev_m": (0.3, "max"),
         "ego.mode_agreement": (0.95, "min"), "tl.agreement": (0.95, "min"), "lane.agreement_min": (0.98, "min"),
         "health.ok": (1.0, "min")}
CONSERVATIVE = {"depth.agreement_min": (0.98, "min"), "seg2d.agreement_min": (0.98, "min")}


def det_match(ga: List[Dict[str, Any]], gb: List[Dict[str, Any]], dist: float) -> int:
    """Greedy one-to-one matches of ``ga`` (by descending score) to ``gb``: same class, centre within ``dist``."""
    used, n = set(), 0
    for a in sorted(ga, key=lambda d: -d["score"]):
        best, bd = None, dist
        for j, b in enumerate(gb):
            if j in used or b["cls"] != a["cls"]:
                continue
            d = math.hypot(a["x"] - b["x"], a["y"] - b["y"])
            if d <= bd:
                best, bd = j, d
        if best is not None:
            used.add(best)
            n += 1
    return n


def _iou2d(a: Dict[str, Any], b: Dict[str, Any]) -> float:
    ix = max(0.0, min(a["cx"] + a["w"] / 2, b["cx"] + b["w"] / 2) - max(a["cx"] - a["w"] / 2, b["cx"] - b["w"] / 2))
    iy = max(0.0, min(a["cy"] + a["h"] / 2, b["cy"] + b["h"] / 2) - max(a["cy"] - a["h"] / 2, b["cy"] - b["h"] / 2))
    inter = ix * iy
    union = a["w"] * a["h"] + b["w"] * b["h"] - inter
    return inter / union if union > 0 else 0.0


def det2d_match(ga: List[Dict[str, Any]], gb: List[Dict[str, Any]], thr: float = 0.5) -> int:
    """Greedy one-to-one matches of the 2D boxes ``ga`` (by descending score) to ``gb``: same class, IoU >= thr."""
    used, n = set(), 0
    for a in sorted(ga, key=lambda d: -d["score"]):
        best, bi = None, thr
        for j, b in enumerate(gb):
            if j in used or b["cls"] != a["cls"]:
                continue
            v = _iou2d(a, b)
            if v >= bi:
                best, bi = j, v
        if best is not None:
            used.add(best)
            n += 1
    return n


def frame_row(gdir: Path, cdir: Path, name: str) -> Dict[str, Any]:
    G = json.loads((gdir / f"{name}.json").read_text())
    Q = json.loads((cdir / f"{name}.json").read_text())
    if G["input_sha256"] != Q.get("input_sha256"):
        raise SystemExit(f"{cdir / name}: inputs differ from the golden's")
    g, q = np.load(gdir / f"{name}.npz"), np.load(cdir / f"{name}.npz")
    r: Dict[str, Any] = {"frame": int(G["frame"])}
    for k in ("lane", "seg2d", "depth", "occ_cls"):
        r[f"{k}_agree"] = float((g[k] == q[k]).mean())
    gb, qb = G["boxes3d"], Q["boxes3d"]
    r["n_ref"], r["n_dev"] = len(gb), len(qb)
    for dist in (0.5, 1.0):
        r[f"m_ref_{dist}"] = det_match(gb, qb, dist)        # reference boxes found by the candidate
        r[f"m_dev_{dist}"] = det_match(qb, gb, dist)        # candidate boxes found in the reference
    g2, q2 = G.get("boxes2d") or [], Q.get("boxes2d") or []
    r["n2_ref"] = sum(len(c) for c in g2)
    r["n2_dev"] = sum(len(c) for c in q2)
    r["m2_ref"] = sum(det2d_match(a, b) for a, b in zip(g2, q2))
    r["m2_dev"] = sum(det2d_match(b, a) for a, b in zip(g2, q2))
    pg, pq = np.asarray(G["ego_paths"]), np.asarray(Q["ego_paths"])
    kg, kq = G["ego"]["mode_selected"], Q["ego"]["mode_selected"]
    r["mode_ref"], r["mode_dev"] = kg, kq
    r["path_dev_same_mode_m"] = float(np.linalg.norm(pg[kg] - pq[kg], axis=1).max())
    r["path_dev_selected_m"] = float(np.linalg.norm(pg[kg] - pq[kq], axis=1).max())
    r["tl_ref"], r["tl_dev"] = G["summary"]["tl"], Q["summary"]["tl"]
    r["stationary_ok_equal"] = bool(G["stationary_head_healthy"]) == bool(Q["stationary_head_healthy"])
    sg, sq = G["summary"]["seg2d_nonbg_frac_per_cam"], Q["summary"]["seg2d_nonbg_frac_per_cam"]
    r["seg2d_nonbg_max_diff"] = float(max(abs(float(sg[k]) - float(sq[k])) for k in sg))
    r["_hm"] = (np.asarray(g["hm"], np.float32), np.asarray(q["hm"], np.float32))
    r["_paths"] = (pg, pq)
    return r


def summarize(rows: List[Dict[str, Any]]) -> Dict[str, Any]:
    n_ref = sum(r["n_ref"] for r in rows)
    n_dev = sum(r["n_dev"] for r in rows)
    s: Dict[str, Any] = {"frames": len(rows), "boxes_ref": n_ref, "boxes_dev": n_dev}
    for dist in (0.5, 1.0):
        rec = sum(r[f"m_ref_{dist}"] for r in rows) / n_ref if n_ref else 1.0
        prec = sum(r[f"m_dev_{dist}"] for r in rows) / n_dev if n_dev else 1.0
        key = "det3d" if dist == 0.5 else "det3d_1m"
        s[f"{key}.recall"], s[f"{key}.precision"] = rec, prec
    n2r, n2d = sum(r["n2_ref"] for r in rows), sum(r["n2_dev"] for r in rows)
    s["det2d.recall"] = sum(r["m2_ref"] for r in rows) / n2r if n2r else 1.0          # information only
    s["det2d.precision"] = sum(r["m2_dev"] for r in rows) / n2d if n2d else 1.0
    s["ego.path_dev_m"] = max(r["path_dev_same_mode_m"] for r in rows)
    s["ego.path_dev_selected_max_m"] = max(r["path_dev_selected_m"] for r in rows)
    s["ego.mode_agreement"] = float(np.mean([r["mode_ref"] == r["mode_dev"] for r in rows]))
    s["tl.agreement"] = float(np.mean([r["tl_ref"] == r["tl_dev"] for r in rows]))
    for k in ("lane", "seg2d", "depth", "occ_cls"):
        v = [r[f"{k}_agree"] for r in rows]
        s[f"{k}.agreement_min"], s[f"{k}.agreement_mean"] = float(min(v)), float(np.mean(v))
    # health: stationary health equal, seg2d non-background fraction close, no frozen outputs
    frozen = 0
    for a, b in zip(rows, rows[1:]):
        if a["frame"] >= b["frame"]:
            continue
        for key in ("_hm", "_paths"):
            ref_moves = not np.array_equal(a[key][0], b[key][0])
            dev_moves = not np.array_equal(a[key][1], b[key][1])
            frozen += ref_moves and not dev_moves
    s["health.stationary_equal"] = all(r["stationary_ok_equal"] for r in rows)
    s["health.seg2d_nonbg_max_diff"] = max(r["seg2d_nonbg_max_diff"] for r in rows)
    s["health.frozen_pairs"] = frozen
    s["health.ok"] = float(s["health.stationary_equal"] and s["health.seg2d_nonbg_max_diff"] <= 0.02 and not frozen)
    return s


def verdict(s: Dict[str, Any], gates: Dict[str, Any]) -> Dict[str, Any]:
    out = {}
    for name, (thr, d) in gates.items():
        v = float(s[name])
        out[name] = {"value": v, "threshold": thr, "pass": v >= thr if d == "min" else v <= thr}
    return out


def stream_drift(cand: Path, acc: Path) -> Dict[str, Any]:
    """Live-stream outputs of two profiles (``stream_fNNNN.npz``): fused lane agreement, mode equality, path gap."""
    out: Dict[str, Any] = {}
    for sid in SETS:
        files = sorted(glob.glob(str(cand / sid / "stream_f*.npz")))
        lanes, modes, paths = [], [], []
        for f in files:
            other = acc / sid / Path(f).name
            if not other.is_file():
                continue
            a, b = np.load(f), np.load(other)
            lanes.append(float((a["lane"] == b["lane"]).mean()))
            modes.append(int(a["mode"]) == int(b["mode"]))
            if a["path"].shape == b["path"].shape and a["path"].size:
                paths.append(float(np.linalg.norm(a["path"] - b["path"], axis=-1).max()))
        if lanes:
            out[sid] = {"frames": len(lanes), "lane_fused_agreement_min": min(lanes),
                        "lane_fused_agreement_last": lanes[-1], "mode_equal": float(np.mean(modes)),
                        "path_gap_max_m": max(paths) if paths else None}
    return out


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("candidate", type=Path)
    ap.add_argument("--accurate", type=Path, help="a --stream run of the accurate profile (stream drift)")
    ap.add_argument("--json", type=Path)
    a = ap.parse_args()
    split_rows: Dict[str, List[Dict[str, Any]]] = {"tune": [], "heldout": []}
    per_set: Dict[str, Any] = {}
    for sid in SETS:
        cdir, gdir = a.candidate / sid, GOLDEN / sid
        names = sorted(Path(p).stem for p in glob.glob(str(cdir / "f[0-9][0-9][0-9][0-9].json")))
        rows = [frame_row(gdir, cdir, n) for n in names]
        if not rows:
            continue
        per_set[sid] = summarize(rows)
        held = HELDOUT.get(sid, False)
        for r in rows:
            is_held = sid in HELDOUT and (held is None or r["frame"] in held)
            split_rows["heldout" if is_held else "tune"].append(r)
    if not per_set:
        print("no candidate frames found", file=sys.stderr)
        return 2
    report: Dict[str, Any] = {"candidate": str(a.candidate), "gates": GATES, "conservative": CONSERVATIVE,
                              "sets": per_set, "splits": {}}
    try:
        run = json.loads((a.candidate / "run.json").read_text())
        report["knobs"] = run.get("knobs")
    except (OSError, ValueError):
        pass
    ok = cons_ok = True
    all_rows = split_rows["tune"] + split_rows["heldout"]
    for split, rows in (("tune", split_rows["tune"]), ("heldout", split_rows["heldout"]), ("all", all_rows)):
        if not rows:
            continue
        s = summarize(rows)
        v, c = verdict(s, GATES), verdict(s, CONSERVATIVE)
        report["splits"][split] = {"summary": s, "verdict": v, "conservative": c}
        ok &= all(x["pass"] for x in v.values())
        cons_ok &= all(x["pass"] for x in c.values())
    if a.accurate:
        report["stream_drift_vs_accurate"] = stream_drift(a.candidate, a.accurate)
    report["pass"], report["pass_conservative"] = bool(ok), bool(cons_ok)
    text = json.dumps(report, indent=1, default=float)
    if a.json:
        a.json.write_text(text + "\n")
    for split, d in report["splits"].items():
        print(split, {k: round(x["value"], 4) for k, x in {**d["verdict"], **d["conservative"]}.items()},
              "PASS" if all(x["pass"] for x in d["verdict"].values()) else "FAIL",
              "| info det2d r/p %.4f / %.4f" % (d["summary"]["det2d.recall"], d["summary"]["det2d.precision"]))
    if "stream_drift_vs_accurate" in report:
        print("stream drift", json.dumps(report["stream_drift_vs_accurate"], default=float))
    print("D21 task gates:", "PASS" if ok else "FAIL", "| conservative depth / seg2d:", "PASS" if cons_ok else "FAIL")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())