rdt2-base-p150 / code /tt_rdt2 /tests /test_config_device.py
changh95's picture
tt-model push rdt2-base-p150 (container)
135fdad verified
Raw History Blame Contribute Delete
10.2 kB
# SPDX-License-Identifier: Apache-2.0
"""Device gates of the configurable step count with the fixed 2 cameras (round 4 stage Config; round 5: the camera
count is fixed at 2, so this file covers the 2-camera configuration only). Every step count of ``RDT2_CFG_STEPS`` is
a freshly built RDT2FMTT on the same device, like a server started with RDT2_NUM_STEPS=S. Run ONLY through the device
lock:
ROOT=<the workspace root>; cd $ROOT/bundles/rdt2-base-p150
TT_METAL_TRACE_ALLOC_TRACKING=1 $ROOT/bin/devrun -t 1800 --reset-on-timeout -- \\
python -u -m pytest -q -s -o faulthandler_timeout=1700 code/tt_rdt2/tests/test_config_device.py
Environment: RDT2_CFG_STEPS (default "1,2,5,8,16"), RDT2_DISPATCH (eth|worker), RDT2_CFG_JSON (where the numbers
are written; default <workspace>/logs/rdt2/r5/impl/gates_steps[_worker].json).
Golden: the official RDT2 inferencer on CPU with the same step count (research/rdt2/golden/config_golden_driver.py:
the checkpoint's 2 cameras, num_inference_timesteps S), 3 cases (first / second / third bucket), fp32 = the
reference, bf16 = the floor run. Nothing was chosen with these cases (hold-out).
Floor of a (case, S) = max(official bf16 run, bf16 reference expert on the official bf16 K/V) per metric
(research/rdt2/config/config_floors.py -> <golden>/config/floors.json); gates as the main suite: 1 - PCC <= max(10 x
floor, 1e-4), group max-abs <= max(3 x floor, 5 mm / 0.01 / 1.5 mm). Without a floor (bf16 run missing) the absolute
limits of the card (PCC >= 0.999, 10 mm / 0.02 / 3 mm) apply and the case is reported as such.
Gates: G-VIS (VISION fed the official pixel_values: image embeds PCC >= 0.999 vs fp32), G-KV-E (the 14 layers' K /
V from the raw request: PCC >= 0.998), and per step count: ENGINES (VISION mk, PREFIX fused, EXPERT mk; no engine
fallback), A2 (every case through the traced call, at the bucket its token count picks), TRACE (the same requests
eagerly after releasing the traces: bit-identical), the memory contract (persistent addresses + allocator state
checked at every replay; run with TT_METAL_TRACE_ALLOC_TRACKING=1).
"""
from __future__ import annotations
import gc
import json
import os
import tempfile
import time
import pytest
import torch
from tt_rdt2.reference.golden import pcc
pytestmark = pytest.mark.device
NCAM = 2 # fixed (round 5): the model card's two wrist cameras
STEPS = [int(s) for s in (os.environ.get("RDT2_CFG_STEPS") or "1,2,5,8,16").split(",")]
DISPATCH = os.environ.get("RDT2_DISPATCH", "eth")
ABS = dict(min_pcc=0.999, pos_m=0.010, rot=0.02, grip_m=0.003)
RESULTS: dict = {"num_cameras": NCAM, "steps": STEPS, "dispatch": DISPATCH, "gates": {}, "runs": {}}
def _golden_dir():
from tt_rdt2.reference.config import DEFAULT_DIRS
return os.path.join(DEFAULT_DIRS["golden"], "config")
def _cases(run="fp32"):
d = os.path.join(_golden_dir(), run)
try:
man = json.load(open(os.path.join(d, "manifest.json")))
except FileNotFoundError:
return {}
return {k: dict(v, path=os.path.join(d, v["file"])) for k, v in man["cases"].items() if v["num_cameras"] == NCAM}
FP32 = _cases("fp32")
BF16 = _cases("bf16")
def _floors():
try:
return json.load(open(os.path.join(_golden_dir(), "floors.json")))
except FileNotFoundError:
return {}
FLOORS = _floors()
def _save():
from tt_rdt2.reference.config import DEV_WORKSPACE
root = str(DEV_WORKSPACE / "logs" / "rdt2" / "r5" / "impl") if DEV_WORKSPACE else tempfile.gettempdir()
sfx = "" if DISPATCH == "eth" else f"_{DISPATCH}"
path = os.environ.get("RDT2_CFG_JSON", os.path.join(root, f"gates_steps{sfx}.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 device():
if not FP32:
pytest.skip(f"no official config golden for {NCAM} camera(s) under {_golden_dir()}")
from tt_rdt2.tt.model import open_rdt2_device
from tt_rdt2.ttaw.device import close_device
dev = open_rdt2_device(DISPATCH)
g = dev.compute_with_storage_grid_size()
RESULTS["grid"] = f"{g.x}x{g.y}"
yield dev
_save()
close_device(dev)
_MODEL = {}
def _model(dev, S):
"""One RDT2FMTT per step count (the previous one released first), like a server started with RDT2_NUM_STEPS=S."""
from tt_rdt2.tt.model import RDT2FMTT
if _MODEL.get("S") != S:
old = _MODEL.pop("m", None)
if old is not None:
old.release()
del old
gc.collect()
t0 = time.time()
m = RDT2FMTT(dev, num_cameras=NCAM, num_steps=S)
_MODEL.update(S=S, m=m, load_s=time.time() - t0)
return _MODEL["m"]
def _load(case, run="fp32"):
return torch.load((FP32 if run == "fp32" else BF16)[case]["path"], map_location="cpu", weights_only=True)
def _request(case, d):
imgs = [x.numpy() for x in d["in.images"]]
return imgs, FP32[case]["prompt"], d["in.state"].numpy(), d["in.noise"]
def _group(a, b):
from tt_rdt2.reference.gatesets import group_maxabs
return group_maxabs(a, b)
def _limits(case, S):
fl = (FLOORS.get(case) or {}).get(str(S))
if not fl:
return None, dict(ABS)
from tt_rdt2.reference.gatesets import limits
lim = limits(fl["floor"])
return fl["floor"], dict(min_pcc=1.0 - lim["one_minus_pcc"], pos_m=lim["pos_m"], rot=lim["rot"], grip_m=lim["grip_m"])
def test_g_vis_and_kv(device):
"""G-VIS and G-KV-E of the 2-camera input (step-count independent; on the first step count's model)."""
import ttnn
from tt_rdt2.tt.vision import host_pixels_from_pixel_values, merged_to_raster
m = _model(device, STEPS[0])
res = {}
for case in FP32:
d = _load(case)
pix = host_pixels_from_pixel_values(d["in.pixel_values"], m.geom)
dst = m.inputs[m.buckets[0]]["pix"]
ttnn.copy_host_to_device_tensor(ttnn.from_torch(pix, dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT), dst, cq_id=0)
img = m.vision.forward(dst)
emb = merged_to_raster(ttnn.to_torch(img).float()[0, 0], m.geom)
ttnn.deallocate(img)
p = pcc(emb, d["vis.image_embeds"])
res[case] = {"vis_pcc": p}
print(f"[cfg c{NCAM}] G-VIS {case}: PCC {p:.6f}", flush=True)
RESULTS["gates"]["g_vis"] = res
assert all(r["vis_pcc"] >= 0.999 for r in res.values()), res
@pytest.mark.parametrize("S", STEPS)
def test_config_steps(device, S):
"""ENGINES + A2 + TRACE (+ G-KV-E on the first step count) for every case at S steps."""
import ttnn
from tt_rdt2.reference.expert import unnormalize_action
from tt_rdt2.tt.model import DEFAULT_ENGINE
m = _model(device, S)
run = {"engine": dict(m.engine), "fallbacks": dict(m.engine_fallbacks), "buckets": list(m.buckets),
"load_s": _MODEL["load_s"], "cases": {}}
RESULTS["runs"][str(S)] = run
# ENGINES: every step count runs the megakernel VISION, the fused PREFIX and the megakernel EXPERT, no fallback
assert m.engine == DEFAULT_ENGINE and not m.engine_fallbacks, (S, m.engine, m.engine_fallbacks)
assert m.buckets == (416, 448, 512) and m.num_steps == S
t0 = time.time()
m.capture()
run["capture_s"] = time.time() - t0
want_bucket = {"grad_short": 0, "real_mid": 1, "noise_long": 2}
traced, fails = {}, []
for case in FP32:
d = _load(case)
imgs, prompt, state, noise = _request(case, d)
o = m(imgs, prompt, state=state, noise=noise)
L = o["bucket"]
ns, act = o["nsample"].clone(), o["action"].clone()
traced[case] = ns
assert L == m.buckets[want_bucket[case.split("_", 1)[1]]], (case, L)
r = {"bucket": L, "n_tokens": o["n_tokens"], "pcc": pcc(ns, d[f"exp.nsample.s{S}"]),
"nsample": ns.reshape(-1).tolist(), "action": act.reshape(-1).tolist()} # re-judged later vs floors
r["pos_m"], r["rot"], r["grip_m"] = _group(act, d[f"out.action.s{S}"])
fl, lim = _limits(case, S)
r["floor"] = fl
r["limits"] = lim
if fl:
r["ratio"] = {"one_minus_pcc": (1 - r["pcc"]) / max(fl["one_minus_pcc"], 1e-12),
**{k: r[k] / max(fl[k], 1e-12) for k in ("pos_m", "rot", "grip_m")}}
r["pass"] = (r["pcc"] >= lim["min_pcc"] and r["pos_m"] <= lim["pos_m"] and r["rot"] <= lim["rot"]
and r["grip_m"] <= lim["grip_m"])
if S == STEPS[0]: # G-KV-E: the K / V of the raw request
n = o["n_tokens"]
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"]])
kp = min(pcc(K[i], d["cond.k"][i]) for i in range(14))
vp = min(pcc(V[i], d["cond.v"][i]) for i in range(14))
r["kv_min_pcc"] = [kp, vp]
if min(kp, vp) < 0.998:
fails.append(f"{case} G-KV-E {kp:.6f}/{vp:.6f}")
if not r["pass"]:
fails.append(f"{case} S={S} A2 pcc {r['pcc']:.6f} pos {r['pos_m']:.5f} rot {r['rot']:.5f} grip "
f"{r['grip_m']:.5f} limits {lim}")
run["cases"][case] = r
rat = r.get("ratio") or {}
print(f"[cfg c{NCAM} S{S}] {case} L={L} n={o['n_tokens']} PCC {r['pcc']:.6f} pos {r['pos_m'] * 1e3:.2f} mm "
f"rot {r['rot']:.4f} grip {r['grip_m'] * 1e3:.2f} mm | ratio to floor "
+ (" ".join(f"{k} {v:.2f}" for k, v in rat.items()) if rat else "(no floor: absolute limits)")
+ f" | {'PASS' if r['pass'] else 'FAIL'}", flush=True)
# TRACE: traced == eager (bit-identical) for the same requests
m.release()
for case in FP32:
d = _load(case)
imgs, prompt, state, noise = _request(case, d)
e = m(imgs, prompt, state=state, noise=noise, traced=False)["nsample"]
same = bool(torch.equal(e, traced[case]))
run["cases"][case]["traced_eq_eager"] = same
if not same:
fails.append(f"{case} S={S} traced != eager")
m.release()
RESULTS["runs"][str(S)] = run
_save()
assert not fails, fails