# SPDX-License-Identifier: Apache-2.0 """Device gates of the RDT2-FM ttnn baseline (one p150, batch 1). Run ONLY through the device lock: ROOT=; cd $ROOT/bundles/rdt2-base-p150 $ROOT/bin/devrun -t 2400 -- python -m pytest -q -s -o faulthandler_timeout=2200 code/tt_rdt2/tests/test_tt_device.py Environment: RDT2_PRECISION (preset of tt/common.py, default the port's default preset), RDT2_DISPATCH (eth|worker), RDT2_ENGINE (per-program engine, e.g. "expert=mk"; default tt/model.py DEFAULT_ENGINE), RDT2_GATES_JSON (where the measured numbers are written; default /logs/rdt2/device/ gates_[_].json in the development checkout, else the temp directory). Gate sets (megakernel workflow, VERIFY_PORT_r2 R2-F1 / F2 / F3; reference/gatesets.py): TUNING = the main golden + the ext golden (may be used to choose a preset); HOLD-OUT = 4 round-2 verifier cases + 4 fresh cases (new real frames / synthetic image, prompts of 420..499 tokens, new seeds and states), never used to choose anything; floor of a case = max(official bf16 run, bf16 reference expert on the official bf16 K/V) per metric (floors.json); A2 verdict = unnormalized group max-abs (position / rotation / gripper) PRIMARY, nsample PCC secondary. Golden sets: ``golden`` = the 13 main cases (prompts of 405 / 409 tokens, bucket 416; states 0 or 0.1 * N(0, 1)); ``golden_ext`` = 5 cases added after the round-1 verification: a 10 * N(0, 1) state (the 0.1 * N(0, 1) states do not move the action) and prompts in the 448 (436 tokens) and 512 (492 tokens) buckets, with ``golden_ext_bf16`` = the same cases run by the official code in bf16 (per-case noise floor). All resident buckets (416 / 448 / 512) are traced. Gates (thresholds anchored on the official bf16-vs-fp32 floor, SPEC section 8.4 and the ext floors): G-VIS image embeds (VISION fed the golden pixels) vs fp32 golden PCC >= 0.999 (floor 0.99987) G-KV K / V of each of the 14 layers, PREFIX fed the golden image rows PCC >= 0.9994 (= official V floor 0.99944; 3 main cases at 416 + the 448-bucket ext case) K floor 0.99995) G-KV-E K / V of each layer from the raw request (VISION + PREFIX) PCC >= 0.998 (below the floor: the ViT at HiFi2 of the default preset costs V PCC there with no effect on the action; ``accurate`` is above the floor) G-EXP expert loop fed the golden K/V, 13 main + 5 ext cases (each at its bucket) nsample PCC >= 0.9999 STATE device EXPERT prologue (adaLN state half): S(s) - S(0) vs the fp32 host form at s = 10 * N(0, 1) PCC >= 0.9999 (the state VALUE path; the main golden states cannot test it) A4-1 one expert step on the DEVICE K/V vs the fp32 reference step on the same K/V velocity PCC >= 0.9999 A4 full expert loop on the DEVICE K/V vs fp32 reference on the same K/V nsample PCC >= 0.9999 (2 main cases at 416 + long_bigstate at 512) TRACE traces captured with request A in the buffers; replaying requests A, C (416) and B (512) is bit-identical to their eager runs (nsample and all K/V); the input buffer addresses never move A2 full traced call from the raw request (bucket picked from the token count): main 13 cases: nsample min PCC >= 0.999, mean >= 0.9995 (floor 0.99992); unnormalized per-group max-abs <= 10 mm position, 0.02 rotation-6D, 3 mm gripper (floor 4.9 mm / 0.0072 / 1.6 mm) every case with its own official bf16 run (3 main + 5 ext): 1 - PCC <= max(10 x (1 - floor), 1e-4), position <= max(3 x floor, 5 mm), rotation <= max(3 x floor, 0.01), gripper <= max(3 x floor, 1.5 mm) NEG negative controls must FAIL A2: swapped cameras, another noise seed, an unrelated instruction (main case); the zero state on the 10 * N(0, 1)-state ext case (proves the state value is load-bearing for A2); on the REAL image (real_ur5e__s0): another instruction and swapped cameras must fail the full A2 criterion (their nsample PCC alone stays above 0.999: the group max-abs limits must catch them) A2-HOLD every hold-out case through the traced call vs its floor (groups primary): reported with the ratio to the floor; asserted for every case not in HOLDOUT_KNOWN_FAIL (each entry documented in MK_LOG.md section 1) BUCKETS the same request at buckets 448 and 512 vs the device's own 416 result: PCC >= 0.99999 and nsample max-abs <= 0.01; the all-valid key mask at 512 (pad keys attended) must FAIL it """ from __future__ import annotations import json import os import tempfile import time import numpy as np import pytest import torch from tt_rdt2.reference.golden import compare, pcc pytestmark = pytest.mark.device # skipped on host-only runs (code/conftest.py) PREC = os.environ.get("RDT2_PRECISION", None) GATES = dict(vis=0.999, kv=0.9994, kv_e2e=0.998, a4_step=0.9999, a4=0.9999, exp=0.9999, state=0.9999, a2_min=0.999, a2_mean=0.9995, pos_m=0.010, rot=0.02, grip_m=0.003, floor_x=10.0, floor_min=1e-4, grp_x=3.0, pos_min_m=0.005, rot_min=0.01, grip_min_m=0.0015, bucket_pcc=0.99999, bucket_maxabs=0.01) RESULTS: dict = {"gates": GATES} ENGINE = os.environ.get("RDT2_ENGINE", "") # hold-out cases that fail their floor with the current VISION + PREFIX (ttnn baseline): measured, documented in # MK_LOG.md section 1 (R2-F1); the test reports them with their ratio to the floor and asserts every other case HOLDOUT_KNOWN_FAIL: dict = {} def _save(): from tt_rdt2.reference.config import DEV_WORKSPACE from tt_rdt2.tt.common import DEFAULT_PRECISION root = str(DEV_WORKSPACE / "logs" / "rdt2" / "device") if DEV_WORKSPACE else tempfile.gettempdir() eng = ("_" + ENGINE.replace("=", "-").replace(",", "_")) if ENGINE else "" path = os.environ.get("RDT2_GATES_JSON", os.path.join(root, f"gates_{PREC or DEFAULT_PRECISION}{eng}.json")) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as f: json.dump(RESULTS, f, indent=1, default=float) @pytest.fixture(scope="module") def model(golden): import ttnn # noqa: F401 from tt_rdt2.tt.model import RDT2FMTT, open_rdt2_device dev = open_rdt2_device(os.environ.get("RDT2_DISPATCH", "eth")) g = dev.compute_with_storage_grid_size() RESULTS["grid"] = f"{g.x}x{g.y}" m = RDT2FMTT(dev, precision=PREC) RESULTS["precision"] = m.prec.as_dict() RESULTS["engine"] = m.engine RESULTS["buckets"] = list(m.buckets) RESULTS["load_s"] = m.timings["load_s"] yield m _save() m.release() from tt_rdt2.ttaw.device import close_device close_device(dev) def _imgs(d): return [d["in.left"].numpy(), d["in.right"].numpy()] def _host(m, d, prompt, images=None, instruction=None, noise=None, state=None, bucket=None): return m.host_inputs(images or _imgs(d), instruction or prompt, d["in.state"] if state is None else state, d["in.noise"] if noise is None else noise, bucket=bucket) def _kv_from_device(m, L, n): import ttnn K = torch.stack([ttnn.to_torch(k).float()[:, :, :n] for k in m.stage_out[L]["K"]]) V = torch.stack([ttnn.to_torch(v).float()[:, :, :n] for v in m.stage_out[L]["V"]]) return K, V def _group_maxabs(a, b): d = (a.reshape(24, 20) - b.reshape(24, 20)).abs() pos = torch.cat([d[:, 0:3], d[:, 10:13]], 1).max().item() rot = torch.cat([d[:, 3:9], d[:, 13:19]], 1).max().item() grip = torch.cat([d[:, 9:10], d[:, 19:20]], 1).max().item() return pos, rot, grip def _floor_limits(fp32, bf16, case=None): """Per-case thresholds from the floor of that case: max(official bf16 run, bf16 reference expert on the official bf16 K/V) per metric (reference/gatesets.py, floors.json; R2-F2), else the official bf16 run alone.""" f = pcc(bf16["exp.nsample"], fp32["exp.nsample"]) fp, fr, fg = _group_maxabs(bf16["out.action"], fp32["out.action"]) fl = _FLOORS.get(case, {}).get("floor") if case else None if fl: f = min(f, 1.0 - fl["one_minus_pcc"]) fp, fr, fg = max(fp, fl["pos_m"]), max(fr, fl["rot"]), max(fg, fl["grip_m"]) G = GATES return dict(floor_pcc=f, floor_pos_m=fp, floor_rot=fr, floor_grip_m=fg, min_pcc=1.0 - max(G["floor_x"] * (1.0 - f), G["floor_min"]), pos_m=max(G["grp_x"] * fp, G["pos_min_m"]), rot=max(G["grp_x"] * fr, G["rot_min"]), grip_m=max(G["grp_x"] * fg, G["grip_min_m"])) def _load_floors(): try: from tt_rdt2.reference.gatesets import load_floors return load_floors() except FileNotFoundError: return {} _FLOORS = _load_floors() def _passes_floor(r, lim): return (r["nsample"]["pcc"] >= lim["min_pcc"] and r["pos_maxabs_m"] <= lim["pos_m"] and r["rot_maxabs"] <= lim["rot"] and r["grip_maxabs_m"] <= lim["grip_m"]) def _ensure_captured(m): if any(t is None for t in m.traces.values()): m.capture() def _a2(m, d, prompt, **kw): """One traced call from the raw request (bucket from the token count unless ``bucket=``).""" from tt_rdt2.reference.expert import unnormalize_action h = _host(m, d, prompt, **kw) L = h["bucket"] _ensure_captured(m) t0 = time.perf_counter() m.write_inputs(h) m.replay(L, blocking=False) ns = m.read_action_normalized(L) dt = (time.perf_counter() - t0) * 1e3 act = unnormalize_action(ns, m.norm)[0] return ns, act, dt, L # --------------------------------------------------------------------------------------------------------------- @pytest.mark.golden @pytest.mark.weights def test_g_vis_image_embeds(model, golden): import ttnn from tt_rdt2.tt.vision import host_pixels_from_pixel_values, merged_to_raster m = model m.release() pix_buf = m.inputs[m.bucket]["pix"] out = {} for case in ("synth_grad__p0__s0", "synth_noise__p0__s0", "synth_blocks__p0__s0", "real_ur5e__s0"): d = golden.load(case) pix = host_pixels_from_pixel_values(d["in.pixel_values"]) ttnn.copy_host_to_device_tensor(ttnn.from_torch(pix, dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT), pix_buf, cq_id=0) img = m.vision.forward(pix_buf) got = merged_to_raster(ttnn.to_torch(img).float()[0, 0]) ttnn.deallocate(img) out[case] = compare(got, d["vis.image_embeds"]) RESULTS["G-VIS"] = out worst = min(v["pcc"] for v in out.values()) print(f"\n[G-VIS] min PCC {worst:.6f}", {k: round(v["pcc"], 6) for k, v in out.items()}) assert worst >= GATES["vis"] @pytest.mark.golden @pytest.mark.weights def test_g_kv_conditioning(model, golden, golden_ext): import ttnn from tt_rdt2.tt.common import upload m = model m.release() out = {} sets = [(golden, c) for c in ("synth_grad__p0__s0", "synth_noise__p1__s0", "real_ur5e__s0")] sets.append((golden_ext, "mid_blocks__bigstate")) # 436 tokens, bucket 448 for gs, case in sets: d = gs.load(case) h = _host(m, d, gs.info(case)["prompt"]) L = h["bucket"] m.write_inputs(h) gimg = torch.zeros(1, 1, 384, 3584) gimg[0, 0, :378] = d["vis.merger_windowed"] gt = upload(gimg, m.device, "bf16") m.prefix.select(L) Ks, Vs = m.prefix.forward(m.inputs[L]["ids"], gt) n = d["cond.k"].shape[3] K = torch.stack([ttnn.to_torch(k).float()[:, :, :n] for k in Ks]) V = torch.stack([ttnn.to_torch(v).float()[:, :, :n] for v in Vs]) for t in (Ks + Vs if not getattr(m.prefix, "persistent_outputs", False) else []) + [gt]: ttnn.deallocate(t) # the PREFIX megakernel's K / V are persistent buffers (never freed) out[case] = {"bucket": L, "K_min_layer": min(pcc(K[i], d["cond.k"][i]) for i in range(14)), "V_min_layer": min(pcc(V[i], d["cond.v"][i]) for i in range(14)), "K": compare(K, d["cond.k"]), "V": compare(V, d["cond.v"])} RESULTS["G-KV"] = out worst = min(min(v["K_min_layer"], v["V_min_layer"]) for v in out.values()) print(f"\n[G-KV] min per-layer PCC {worst:.6f}", {k: (v["bucket"], round(v["K_min_layer"], 6), round(v["V_min_layer"], 6)) for k, v in out.items()}) assert worst >= GATES["kv"] @pytest.mark.golden @pytest.mark.weights def test_expert_on_golden_kv(model, golden, golden_ext): import ttnn from tt_rdt2.reference.preprocess import choose_bucket from tt_rdt2.tt.common import upload from tt_rdt2.tt.expert import host_mask, host_noise, host_state m = model m.release() out = {} for gs, case in [(golden, c) for c in golden.cases] + [(golden_ext, c) for c in golden_ext.cases]: d = gs.load(case) n = d["cond.k"].shape[3] L = choose_bucket(n, m.buckets) ns = m.expert_on_kv(d["cond.k"], d["cond.v"], d["in.noise"], d["in.state"], L) out[case] = dict(compare(ns, d["exp.nsample"]), bucket=L) RESULTS["G-EXP"] = out worst = min(v["pcc"] for v in out.values()) print(f"\n[G-EXP] nsample min PCC {worst:.7f} max_abs {max(v['max_abs'] for v in out.values()):.5f}", {k: round(v["pcc"], 7) for k, v in out.items() if k in golden_ext.cases}) assert worst >= GATES["exp"] @pytest.mark.golden @pytest.mark.weights def test_state_prologue(model, expert): """The adaLN state half of the device prologue tracks the state VALUE: S(s) - S(0) vs the fp32 host form.""" import ttnn from tt_rdt2.tt.common import upload from tt_rdt2.tt.expert import host_state, state_half_host m = model m.release() def dev_S(state): sdev = upload(host_state(state), m.device, "fp32") S = m.expert.prologue(sdev) if isinstance(S, dict): # ttnn expert: one (1, 1, 1, 1024) tensor per chunk o = {k: ttnn.to_torch(v).float().reshape(-1)[:1024] for k, v in S.items()} for v in list(S.values()): ttnn.deallocate(v) else: # megakernel: one S_all (1, 1, 1, 131072) fp32 o = type(m.expert).state_half_dict(S) ttnn.deallocate(S) ttnn.deallocate(sdev) return o z = torch.zeros(20) big = 10.0 * torch.randn(20, generator=torch.Generator().manual_seed(31)) rz, rb = state_half_host(expert, z), state_half_host(expert, big) dz, db = dev_S(z), dev_S(big) keys = list(rz) dd = torch.cat([db[k] - dz[k] for k in keys]) dr = torch.cat([rb[k] - rz[k] for k in keys]) out = dict(delta_pcc=pcc(dd, dr), delta_ref_absmax=float(dr.abs().max()), delta_err_absmax=float((dd - dr).abs().max()), S_big_min_pcc=min(pcc(db[k], rb[k]) for k in keys), S_zero_min_pcc=min(pcc(dz[k], rz[k]) for k in keys)) # negative control: a device prologue that ignored the state would give a zero delta (PCC undefined -> 0) RESULTS["STATE"] = out print("\n[STATE]", {k: round(v, 7) for k, v in out.items()}) assert out["delta_pcc"] >= GATES["state"] @pytest.mark.golden @pytest.mark.weights def test_a4_expert_on_device_conditioning(model, golden, golden_ext, expert): """Expert on the device K/V (VISION + PREFIX from the raw request) vs the fp32 reference expert on the same K/V.""" import ttnn from tt_rdt2.reference.expert import euler_timesteps m = model m.release() out = {} sets = [(golden, "synth_grad__p0__s1"), (golden, "real_ur5e__s0"), (golden_ext, "long_bigstate")] for gs, case in sets: d = gs.load(case) h = _host(m, d, gs.info(case)["prompt"]) L = h["bucket"] m.write_inputs(h) m.run_eager(L) n = int(h["n_tokens"]) K, V = _kv_from_device(m, L, n) ns_dev = m.read_action_normalized(L) mask = torch.ones(1, n, dtype=torch.bool) inp = m.inputs[L] if m.engine["expert"] == "mk": # one Euler step of the program: v0 = (a_1 - noise) / dt (fp32 state) S = m.expert.prologue(inp["state"]) y = m.expert.run(L, m.stage_out[L]["K"], m.stage_out[L]["V"], inp["mask"], inp["noise"], S, nsteps=1) a1 = ttnn.to_torch(y).float()[0, 0, :24, :20][None] ttnn.deallocate(S) v0_dev = (a1 - d["in.noise"].float()) / float(torch.tensor(0.2, dtype=torch.float32)) else: taps = {} a = m.expert.forward(inp["noise"], inp["state"], m.stage_out[L]["K"], m.stage_out[L]["V"], inp["mask"], taps=taps) v0_dev = ttnn.to_torch(taps["exp.step0.velocity"]).float()[0, 0, :24, :20][None] for t in list(taps.values()) + [a]: ttnn.deallocate(t) ex = expert s = ex.state_cond(d["in.state"]) tparts = ex.precompute_time_part(euler_timesteps()) sb, sf = ex.precompute_state_part(s) tb, tf = tparts[0] v0_ref = ex.velocity(d["in.noise"], [tb[i] + sb[i] for i in range(14)], tf + sf, K, V, mask) ns_ref = ex.sample(d["in.noise"], d["in.state"], K, V, mask) out[case] = {"bucket": L, "step0_velocity": compare(v0_dev, v0_ref), "nsample": compare(ns_dev, ns_ref), "nsample_vs_golden": compare(ns_dev, d["exp.nsample"])} RESULTS["A4"] = out w1 = min(v["step0_velocity"]["pcc"] for v in out.values()) w2 = min(v["nsample"]["pcc"] for v in out.values()) print(f"\n[A4] step0 velocity min PCC {w1:.7f}; nsample min PCC {w2:.7f}", {k: (v["bucket"], round(v["nsample"]["pcc"], 7)) for k, v in out.items()}) assert w1 >= GATES["a4_step"] assert w2 >= GATES["a4"] @pytest.mark.golden @pytest.mark.weights def test_trace_bitexact_and_kv_e2e(model, golden, golden_ext): """Eager runs of A, C (416) and B (512) first; then the traces are captured with A's inputs in the buffers and replayed on A, C and B: every replay must equal its eager run bit for bit (the trace reads every input buffer).""" m = model m.release() reqs = {"A": (golden, "synth_blocks__p1__s1"), "C": (golden_ext, "real_ur5e__bigstate"), "B": (golden_ext, "long_bigstate")} host, eager, data = {}, {}, {} for key, (gs, case) in reqs.items(): d = gs.load(case) h = _host(m, d, gs.info(case)["prompt"]) L, n = h["bucket"], int(h["n_tokens"]) m.write_inputs(h) m.run_eager(L) eager[key] = (m.read_action_normalized(L), *_kv_from_device(m, L, n)) host[key], data[key] = h, d addr = lambda: {f"{L}.{k}": int(t.buffer_address()) for L, inp in m.inputs.items() for k, t in inp.items()} a0 = addr() m.write_inputs(host["A"]) m.capture() out = {} for key in ("A", "C", "B", "A"): h = host[key] L, n = h["bucket"], int(h["n_tokens"]) m.write_inputs(h) m.replay(L, blocking=True) ns_t = m.read_action_normalized(L) K_t, V_t = _kv_from_device(m, L, n) ns_e, K_e, V_e = eager[key] d = data[key] out[f"{key}:{reqs[key][1]}@{L}"] = { "nsample_bitexact": bool(torch.equal(ns_e, ns_t)), "K_bitexact": bool(torch.equal(K_e, K_t)), "V_bitexact": bool(torch.equal(V_e, V_t)), "K_min_layer": min(pcc(K_e[i], d["cond.k"][i]) for i in range(14)), "V_min_layer": min(pcc(V_e[i], d["cond.v"][i]) for i in range(14))} out["input_addresses_stable"] = addr() == a0 if m.engine["expert"] == "mk": # persistent per-bucket output tiles: 416's output survives the 512 replay m.write_inputs(host["C"]) m.replay(416, blocking=True) keep = m.read_action_normalized(416).clone() m.write_inputs(host["B"]) m.replay(512, blocking=True) out["output_416_survives_512_replay"] = bool(torch.equal(m.read_action_normalized(416), keep)) out["persistent_addresses_checked"] = True m.check_persistent() # memory contract (VERIFY_MK_r1 R1-F2): a buffer allocated after the capture and alive at a replay is refused; # once it is freed the replays run again; the ttnn PREFIX refuses new bucket tables after the seal import ttnn leak = ttnn.from_torch(torch.zeros(1, 1, 32, 32), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=m.device, memory_config=ttnn.DRAM_MEMORY_CONFIG) try: with pytest.raises(RuntimeError, match="memory contract"): m.replay(416, blocking=True) finally: ttnn.deallocate(leak) m.replay(416, blocking=True) out["memory_contract_enforced"] = True if m.engine["prefix"] in ("ttnn", "fused"): with pytest.raises(RuntimeError, match="memory contract"): m.prefix.add_bucket(480) out["add_bucket_refused_after_seal"] = True RESULTS["TRACE"] = out print("\n[TRACE]", json.dumps(out, default=float)) assert out["input_addresses_stable"] assert out.get("output_416_survives_512_replay", True) for k, v in out.items(): if isinstance(v, dict): assert v["nsample_bitexact"] and v["K_bitexact"] and v["V_bitexact"], k assert min(v["K_min_layer"], v["V_min_layer"]) >= GATES["kv_e2e"], k @pytest.mark.golden @pytest.mark.weights def test_a2_e2e_all_golden_cases(model, golden, golden_bf16, golden_ext, golden_ext_bf16): m = model out, ext = {}, {} floors = {c: (golden_bf16, golden) for c in golden_bf16.cases} floors.update({c: (golden_ext_bf16, golden_ext) for c in golden_ext_bf16.cases}) for gs, dst in ((golden, out), (golden_ext, ext)): for case in gs.cases: d = gs.load(case) ns, act, dt, L = _a2(m, d, gs.info(case)["prompt"]) pos, rot, grip = _group_maxabs(act, d["out.action"]) r = {"bucket": L, "nsample": compare(ns, d["exp.nsample"]), "action": compare(act, d["out.action"]), "pos_maxabs_m": pos, "rot_maxabs": rot, "grip_maxabs_m": grip, "call_ms": dt} if case in floors: fb, ff = floors[case] r["floor"] = _floor_limits(d, fb.load(case, with_vlm=False), case) r["floor_pass"] = _passes_floor(r, r["floor"]) dst[case] = r RESULTS["A2"] = out RESULTS["A2_ext"] = ext p = [v["nsample"]["pcc"] for v in out.values()] print(f"\n[A2] main nsample PCC min {min(p):.6f} mean {np.mean(p):.6f}; max-abs pos " f"{max(v['pos_maxabs_m'] for v in out.values()) * 1e3:.2f} mm rot " f"{max(v['rot_maxabs'] for v in out.values()):.4f} grip " f"{max(v['grip_maxabs_m'] for v in out.values()) * 1e3:.2f} mm") for k, v in list(out.items()) + list(ext.items()): fl = v.get("floor") print(f" {k:24s} L{v['bucket']} nsample pcc {v['nsample']['pcc']:.6f} max_abs {v['nsample']['max_abs']:.4f} " f"pos {v['pos_maxabs_m'] * 1e3:.2f} mm rot {v['rot_maxabs']:.4f} grip {v['grip_maxabs_m'] * 1e3:.2f} mm" + (f" | floor {fl['floor_pcc']:.6f} -> min {fl['min_pcc']:.6f}, grip <= {fl['grip_m'] * 1e3:.2f} mm, " f"pos <= {fl['pos_m'] * 1e3:.1f} mm, rot <= {fl['rot']:.4f}: {'pass' if v['floor_pass'] else 'FAIL'}" if fl else "")) assert min(p) >= GATES["a2_min"] and np.mean(p) >= GATES["a2_mean"] assert max(v["pos_maxabs_m"] for v in out.values()) <= GATES["pos_m"] assert max(v["rot_maxabs"] for v in out.values()) <= GATES["rot"] assert max(v["grip_maxabs_m"] for v in out.values()) <= GATES["grip_m"] assert all(v["nsample"]["pcc"] >= GATES["a2_min"] for v in ext.values()) assert set(golden_ext.cases) <= set(golden_ext_bf16.cases) for k, v in list(out.items()) + list(ext.items()): if "floor" in v: assert v["floor_pass"], f"{k} misses its floor-anchored A2 thresholds" @pytest.mark.golden @pytest.mark.weights def test_negative_controls(model, golden, golden_ext, golden_ext_bf16): """Perturbed inputs must fail the A2 gate (proves the gate can fail).""" m = model case = "synth_grad__p0__s0" d = golden.load(case) pr = golden.info(case)["prompt"] out = {} ns, _, _, _ = _a2(m, d, pr, images=[d["in.right"].numpy(), d["in.left"].numpy()]) out["swapped_cameras"] = compare(ns, d["exp.nsample"]) ns, _, _, _ = _a2(m, d, pr, noise=torch.randn((1, 24, 20), generator=torch.Generator().manual_seed(123))) out["other_noise_seed"] = compare(ns, d["exp.nsample"]) ns, _, _, _ = _a2(m, d, pr, instruction="Wipe the table with the white cloth.") out["other_instruction"] = compare(ns, d["exp.nsample"]) # the state value: the 10 * N(0, 1)-state case fed a zero state must miss its floor-anchored A2 thresholds case = "real_ur5e__bigstate" d = golden_ext.load(case) ns, act, _, _ = _a2(m, d, golden_ext.info(case)["prompt"], state=np.zeros(20, np.float32)) pos, rot, grip = _group_maxabs(act, d["out.action"]) r = {"nsample": compare(ns, d["exp.nsample"]), "pos_maxabs_m": pos, "rot_maxabs": rot, "grip_maxabs_m": grip} lim = _floor_limits(d, golden_ext_bf16.load(case), case) out["zero_state_on_bigstate_case"] = dict(r["nsample"], floor_min_pcc=lim["min_pcc"], floor_pass=_passes_floor(r, lim)) # real image (R2-F3): another instruction / swapped cameras keep nsample PCC > 0.999; the full A2 criterion # (PCC and the group max-abs limits) must reject them case = "real_ur5e__s0" d = golden.load(case) pr = golden.info(case)["prompt"] for name, kw in (("real_other_instruction", dict(instruction="Wipe the table with the white cloth.")), ("real_swapped_cameras", dict(images=[d["in.right"].numpy(), d["in.left"].numpy()]))): ns, act, _, _ = _a2(m, d, pr, **kw) pos, rot, grip = _group_maxabs(act, d["out.action"]) r = dict(compare(ns, d["exp.nsample"]), pos_maxabs_m=pos, rot_maxabs=rot, grip_maxabs_m=grip) r["a2_pass"] = (r["pcc"] >= GATES["a2_min"] and pos <= GATES["pos_m"] and rot <= GATES["rot"] and grip <= GATES["grip_m"]) out[name] = r RESULTS["NEG"] = out print("\n[NEG]", {k: (round(v["pcc"], 5), round(v.get("pos_maxabs_m", 0) * 1e3, 1)) for k, v in out.items()}) for k, v in out.items(): if k == "zero_state_on_bigstate_case": assert not v["floor_pass"], "the zero-state control passed the floor-anchored A2 gate" elif k.startswith("real_"): assert not v["a2_pass"], f"real-image negative control {k} passed the full A2 criterion" else: assert v["pcc"] < GATES["a2_min"], f"negative control {k} passed the gate" @pytest.mark.golden @pytest.mark.weights def test_buckets_and_pad_mask(model, golden): """The same request at buckets 448 / 512 (right padding, pad keys masked) equals the device's own 416 result; with the pad keys left unmasked (all-valid mask) at 512 it must not.""" from tt_rdt2.tt.prefix import host_ids from tt_rdt2.tt.expert import host_mask m = model _ensure_captured(m) case = "real_ur5e__s0" d = golden.load(case) pr = golden.info(case)["prompt"] ref, _, _, L0 = _a2(m, d, pr, bucket=416) out = {"416_vs_golden": compare(ref, d["exp.nsample"])} def ok(r): return r["pcc"] >= GATES["bucket_pcc"] and r["max_abs"] <= GATES["bucket_maxabs"] for L in (448, 512): ns, _, _, _ = _a2(m, d, pr, bucket=L) out[str(L)] = dict(compare(ns, ref), vs_golden=pcc(ns, d["exp.nsample"])) h = _host(m, d, pr, bucket=512) n = int(h["n_tokens"]) h["mask"] = host_mask(torch.ones(512, dtype=torch.bool)) # pad keys attended (the mask a broken port would have) m.write_inputs(h) m.replay(512, blocking=False) ns = m.read_action_normalized(512) out["512_unmasked"] = dict(compare(ns, ref), vs_golden=pcc(ns, d["exp.nsample"]), pad_keys=512 - n) with pytest.raises(ValueError): # a prompt never lands in a bucket shorter than itself (never truncated) host_ids(torch.zeros(1, 449, dtype=torch.long), 448) RESULTS["BUCKETS"] = out print("\n[BUCKETS]", {k: (round(v["pcc"], 7), round(v["max_abs"], 5)) for k, v in out.items()}) assert ok(out["448"]) and ok(out["512"]) assert not ok(out["512_unmasked"]), "the unmasked-pad control passed the bucket gate" @pytest.mark.golden @pytest.mark.weights def test_a2_holdout(model): """HOLD-OUT cases (never used to choose anything) through the traced call vs their floors (groups primary). Reported with the ratio to the floor; every case not in HOLDOUT_KNOWN_FAIL must pass.""" from tt_rdt2.reference.gatesets import HoldoutSet, judge hs = HoldoutSet() if not hs.cases: pytest.skip("hold-out golden not found") missing = [c for c in hs.cases if c not in _FLOORS] # VERIFY_MK_r1 R1-F3: no hold-out case goes unjudged assert not missing, f"hold-out cases without a floor in floors.json (run gatesets.compute_floors): {missing}" m = model out = {} for case in hs.cases: d = hs.load(case) ns, act, dt, L = _a2(m, d, d["meta.prompt"]) pos, rot, grip = _group_maxabs(act, d["out.action"]) got = dict(one_minus_pcc=1 - pcc(ns, d["exp.nsample"]), pos_m=pos, rot=rot, grip_m=grip) r = dict(bucket=L, got=got, call_ms=dt, verdict=judge(got, _FLOORS[case]["floor"])) out[case] = r RESULTS["A2_HOLDOUT"] = out print("\n[A2-HOLD]") for k, v in out.items(): g = v["got"] line = (f" {k:22s} L{v['bucket']} 1-PCC {g['one_minus_pcc']:.2e} pos {g['pos_m'] * 1e3:.2f} mm " f"rot {g['rot']:.4f} grip {g['grip_m'] * 1e3:.2f} mm") if "verdict" in v: rt = v["verdict"]["ratio_to_floor"] line += (f" | x floor pcc {rt['one_minus_pcc']:.1f} pos {rt['pos_m']:.1f} rot {rt['rot']:.1f} " f"grip {rt['grip_m']:.1f}: {'pass' if v['verdict']['passed'] else 'FAIL'}") print(line) for k, v in out.items(): if k not in HOLDOUT_KNOWN_FAIL: assert v["verdict"]["passed"], f"hold-out case {k} misses its floor ({v['verdict']['ratio_to_floor']})"