File size: 6,356 Bytes
7a24154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Held-out non-regression gate: every converted public frame that the frozen frame gates do NOT use, through the
served ``model()`` path, against the fp32 CPU reference (needs one p150 and the workspace's public data).

    bin/devrun -t 1800 -- python -u -m pytest -q -s -o faulthandler_timeout=1500 code/tt_frnet/tests/test_heldout_device.py

Why (independent verification of OPT rounds 1-4, finding F1, 2026-10-14): r1.1 KCAT lowered the OT128 agreement on
frames outside the gate set (nuScenes scene-0916: 2 -> 5 frames below 98.5 %) while every frozen gate stayed green.
This test closes that hole: ``research/frnet/public_data/inputs`` holds 32 PandaSet + 81 nuScenes frames (113); the
ones not in ``_data.PUBLIC_OT128`` / ``PUBLIC_QT128`` (97 OT128 / 109 QT128 frames) run through
``FRNet.__call__`` with their sensor -> base_link transform, and each point's label is compared with the ONNX Runtime
fp32 CPU run of the same frame (``public_data/runs/<frame>_<variant>.npz``).

Gates (non-regression against the published baseline release, ``c006379`` = ``7a31376``'s device graph, measured by
the verification: ``logs/frnet/verify_opt_r1/heldout_base_<variant>.json``; thresholds are the baseline value minus a
noise margin for the agreement statistics and the baseline count for the frames below the 98.5 % frame threshold):

======================================  ===============  =============================
gate                                    baseline value   threshold
======================================  ===============  =============================
ot128.heldout.mean_argmax_agreement     0.992889         >= 0.9927
ot128.heldout.min_argmax_agreement      0.98374          >= 0.9830
ot128.heldout.frames_below_0985         2                <= 2
qt128.heldout.mean_argmax_agreement     0.993987         >= 0.9938
qt128.heldout.min_argmax_agreement      0.98105          >= 0.9805
qt128.heldout.frames_below_0985         1                <= 1
======================================  ===============  =============================

The baseline itself has frames below 98.5 % here (ot128 2, qt128 1, all nuScenes scene-0916): the frozen per-frame
98.5 % gate of ``test_e2e_device.py`` holds on its pinned frames only. Every frame is reported in
``logs/frnet/heldout_<variant>[TAG].json``.
"""
from __future__ import annotations

import json
import os
import time

import numpy as np
import pytest

from tt_frnet.tests import _data
from tt_frnet.ttaw.golden import GateRegistry

pytestmark = pytest.mark.device

VARIANTS = ("ot128", "qt128")
IGNORE = 255
PUBLIC = _data.WORKSPACE / "research" / "frnet" / "public_data"
LOG_DIR = _data.WORKSPACE / "logs" / "frnet"
TAG = os.environ.get("FRNET_E2E_TAG", "")
GATES = GateRegistry.for_test(__file__, {
    "ot128.heldout.mean_argmax_agreement": (0.9927, "min", "argmax_agreement"),
    "ot128.heldout.min_argmax_agreement": (0.9830, "min", "argmax_agreement"),
    "ot128.heldout.frames_below_0985": (2, "max", "frame_count"),
    "qt128.heldout.mean_argmax_agreement": (0.9938, "min", "argmax_agreement"),
    "qt128.heldout.min_argmax_agreement": (0.9805, "min", "argmax_agreement"),
    "qt128.heldout.frames_below_0985": (1, "max", "frame_count"),
})
# Held-out frames per variant (113 public inputs minus the frame-gate frames): a missing frame fails the test.
EXPECTED_FRAMES = {"ot128": 97, "qt128": 109}


def heldout_frames(variant: str):
    gated = set(_data.PUBLIC_OT128 if variant == "ot128" else _data.PUBLIC_QT128)
    names = sorted(p.stem for p in (PUBLIC / "inputs").glob("*.npz"))
    return [n for n in names if n not in gated]


@pytest.fixture(scope="module", params=VARIANTS)
def model(request, device):
    from tt_frnet import FRNet

    m = FRNet.from_pretrained(device=device, variant=request.param, weights_dir=str(_data.weights_dir()))
    yield m
    m.close()


def test_heldout_frames(model):
    v = model.variant
    _data.need((PUBLIC / "inputs").is_dir() and (PUBLIC / "runs").is_dir(), f"public data under {PUBLIC}")
    names = heldout_frames(v)
    assert len(names) == EXPECTED_FRAMES[v], (len(names), EXPECTED_FRAMES[v])
    rep = {"variant": v, "frames": {}, "knobs": None}
    knobs = getattr(getattr(model, "graph", None), "knobs", None)
    if knobs is not None:
        rep["knobs"] = {k: str(x) for k, x in knobs.items()}
    t0 = time.perf_counter()
    for n in names:
        z = np.load(PUBLIC / "inputs" / f"{n}.npz", allow_pickle=False)
        run = np.load(PUBLIC / "runs" / f"{n}_{v}.npz", allow_pickle=False)
        xyzi = np.ascontiguousarray(z["xyzi"], np.float32)
        cpu = np.full(len(xyzi), IGNORE, np.uint8)
        cpu[run["input_rows"]] = run["class_id"]
        res = model(xyzi, calibration={"T_base_link_from_sensor": z["T_base_link_sensor"].tolist()})
        assert not res.meta.get("skipped"), (n, res.meta.get("skipped"))
        pred = np.full(len(xyzi), IGNORE, np.uint8)
        pred[res.input_index] = res.label_ids[: res.num_points_raw]
        scored = cpu != IGNORE
        assert np.array_equal(pred != IGNORE, scored), f"{n}: the device and the CPU run keep different points"
        rep["frames"][n] = float(np.mean(pred[scored] == cpu[scored]))
    rep["seconds"] = time.perf_counter() - t0
    a = np.array(list(rep["frames"].values()))
    rep["mean"], rep["min"], rep["median"] = float(a.mean()), float(a.min()), float(np.median(a))
    rep["min_frame"] = min(rep["frames"], key=rep["frames"].get)
    rep["below_0985"] = sorted(k for k, x in rep["frames"].items() if x < 0.985)
    results = {
        f"{v}.heldout.mean_argmax_agreement": rep["mean"],
        f"{v}.heldout.min_argmax_agreement": rep["min"],
        f"{v}.heldout.frames_below_0985": float(len(rep["below_0985"])),
    }
    rep["gates"] = {k: {"value": x, "passed": GATES.check(k, x).passed} for k, x in results.items()}
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    (LOG_DIR / f"heldout_{v}{TAG}.json").write_text(json.dumps(rep, indent=1, default=float))
    print(f"\n{v} held-out ({len(a)} frames, {rep['seconds']:.0f} s): mean {rep['mean']:.6f} min {rep['min']:.5f} "
          f"({rep['min_frame']}) below 98.5 %: {rep['below_0985']}", flush=True)
    failed = [k for k, r in rep["gates"].items() if not r["passed"]]
    assert not failed, {k: rep["gates"][k] for k in failed}