rdt2-base-p150 / code /tt_rdt2 /tests /test_tt_host.py
changh95's picture
tt-model push rdt2-base-p150 (container)
9d8d25c verified
Raw History Blame Contribute Delete
13.4 kB
# SPDX-License-Identifier: Apache-2.0
"""Host proofs (no device) of every layout / decomposition the ttnn port uses, against the fp32 reference.
Each test emulates the device formulation in fp32 torch with the exact host tensors the port uploads:
* pixels: window-order normalized patch rows == golden pixel_values (permuted, first frame), all cases
* ViT attention: per-head pairwise q/k permutation + 96 padding + pairwise RoPE tables + windowed attention with the
pad window + padded proj == reference block (real weights of blocks 0 and 7)
* PREFIX: bucket mRoPE positions, one-hot scatter (inverse window permutation), host ids / key mask
* EXPERT: adaLN time/state split folded into (gamma, beta, gate), the 32-row layout (registers, pad rows, windowed
self-attention, masked Euler update in fp32) == reference sampler on every golden case
Run: TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_rdt2/tests/test_tt_host.py
"""
from __future__ import annotations
import pytest
import torch
import torch.nn.functional as F
from tt_rdt2.reference.config import CONFIG, IMAGE_TOKEN_ID, PAD_TOKEN_ID
from tt_rdt2.reference.golden import pcc
from tt_rdt2.reference.ops import rms_norm
E = CONFIG.expert
V = CONFIG.vision
@pytest.mark.golden
def test_host_pixels_all_cases(golden):
from tt_rdt2.tt.vision import host_pixels, host_pixels_from_pixel_values
for case in golden.cases:
d = golden.load(case, with_vlm=True)
a = host_pixels([d["in.left"].numpy(), d["in.right"].numpy()])
b = host_pixels_from_pixel_values(d["in.pixel_values"])
assert torch.equal(a, b), case
def _vision_block_device_form(w, i, x_win, full: bool):
"""fp32 emulation of VisionTT.block on (1536, 1280) window-order rows."""
from tt_rdt2.tt.vision import HD, HDP, N_PATCH, N_ROWS, _qk_rows, _v_rows, vision_cu_seqlens, vision_rope_tables
p = f"visual.blocks.{i}."
qkv_w = w[p + "attn.qkv.weight"].float()
qkv_b = w[p + "attn.qkv.bias"].float()
qw, kw, vw = qkv_w.split(V.hidden, 0)
qb, kb, vb = qkv_b.split(V.hidden, 0)
Wq = torch.cat([_qk_rows(qw), _qk_rows(kw), _v_rows(vw)], 0)
Bq = torch.cat([_qk_rows(qb), _qk_rows(kb), _v_rows(vb)], 0)
x = torch.zeros(N_ROWS, V.hidden)
x[:N_PATCH] = x_win
h = rms_norm(x, w[p + "norm1.weight"].float(), V.norm_eps)
qkv = F.linear(h, Wq, Bq)
q, k, v = qkv.reshape(N_ROWS, 3, V.heads, HDP).permute(1, 2, 0, 3) # (H, S, 96)
rt = vision_rope_tables()
cos, sin = rt["cos"][0, 0], rt["sin"][0, 0]
def rope(t):
t2 = t.reshape(V.heads, N_ROWS, HDP // 2, 2)
rot = torch.stack([-t2[..., 1], t2[..., 0]], -1).reshape(V.heads, N_ROWS, HDP)
return t * cos + rot * sin
q, k = rope(q), rope(k)
cu = vision_cu_seqlens()["full" if full else "window"]
o = torch.zeros_like(q)
for a, b in zip(cu[:-1], cu[1:]):
o[:, a:b] = F.scaled_dot_product_attention(q[:, a:b], k[:, a:b], v[:, a:b], scale=HD ** -0.5)
oc = o.transpose(0, 1).reshape(N_ROWS, V.heads * HDP)
proj = w[p + "attn.proj.weight"].float().t().reshape(V.heads, HD, V.hidden)
proj = torch.cat([proj, proj.new_zeros(V.heads, HDP - HD, V.hidden)], 1).reshape(-1, V.hidden)
x = x + oc @ proj + w[p + "attn.proj.bias"].float()
h = rms_norm(x, w[p + "norm2.weight"].float(), V.norm_eps)
g = F.linear(h, w[p + "mlp.gate_proj.weight"].float(), w[p + "mlp.gate_proj.bias"].float())
u = F.linear(h, w[p + "mlp.up_proj.weight"].float(), w[p + "mlp.up_proj.bias"].float())
x = x + F.linear(F.silu(g) * u, w[p + "mlp.down_proj.weight"].float(), w[p + "mlp.down_proj.bias"].float())
return x[:N_PATCH]
@pytest.mark.weights
@pytest.mark.golden
def test_vision_attention_layout(golden, dirs):
from tt_rdt2.reference.vision import VisionTower
from tt_rdt2.reference.preprocess import vision_geometry
from tt_rdt2.reference.weights import load_vlm_index
idx = load_vlm_index()
names = [k for k in idx.keys() if k.startswith(("visual.blocks.0.", "visual.blocks.7."))]
w = idx.load(names)
vt = VisionTower({**w, "visual.patch_embed.proj.weight": torch.zeros(1280, 3, 2, 14, 14)})
d = golden.load("synth_grad__p0__s0")
geom = vision_geometry(torch.tensor([[1, 28, 54]]))
x0 = d["vis.patch_embed"][geom["patch_perm"]]
for i, full in ((0, False), (7, True)):
cu = geom["cu_full"] if full else geom["cu_window"]
ref = vt.block(i, x0, geom["cos"], geom["sin"], cu)
got = _vision_block_device_form(w, i, x0, full)
assert pcc(got, ref) > 0.9999999, i
assert (got - ref).abs().max() < 1e-3 * ref.abs().max(), i
@pytest.mark.golden
def test_prefix_host_layout(golden):
from tt_rdt2.reference.preprocess import bucket_inputs
from tt_rdt2.tt.prefix import IMAGE_START, ZERO_ROW, bucket_positions, host_ids, scatter_matrix
for L in (416, 448, 512):
S = scatter_matrix(L)[0, 0]
assert S.sum() == 378 and (S.sum(0)[:378] == 1).all() and (S.sum(0)[378:] == 0).all()
for case in ("synth_grad__p0__s0", "synth_noise__p1__s0", "real_ur5e__s0"):
d = golden.load(case)
ids = d["in.input_ids"]
n = ids.shape[1]
for L in (416, 448, 512):
pos = bucket_positions(L)
assert torch.equal(pos[:, :, :n], d["llm.position_ids"])
ref_b = bucket_inputs({"input_ids": ids, "position_ids": d["llm.position_ids"],
"attention_mask": torch.ones_like(ids)}, L)
assert torch.equal(pos, ref_b["position_ids"])
bids, km = host_ids(ids, L)
assert km.sum() == n and km[:n].all()
exp = ref_b["input_ids"][0].clone()
exp[exp == IMAGE_TOKEN_ID] = ZERO_ROW
assert torch.equal(bids[0].long(), exp)
assert (bids[0, n:] == PAD_TOKEN_ID).all()
x = scatter_matrix(416)[0, 0, :, :378] @ d["vis.merger_windowed"]
assert torch.equal(x[IMAGE_START:IMAGE_START + 378], d["vis.image_embeds"])
def test_prefix_k_bias_tables():
"""lm_kscore "table" (VERIFY_MK_r1 R1-F1): RoPE(W h) + T == RoPE(W h + b) (the K output), and the score operand
RoPE(W h) + D gives the same causal softmax as the full k (D = T - mean_j T differs from T by a constant)."""
from tt_rdt2.reference.preprocess import mrope_cos_sin
from tt_rdt2.reference.ops import rotate_half
from tt_rdt2.tt.prefix import bucket_positions, k_bias_tables
g = torch.Generator().manual_seed(3)
for L in (416, 512):
cos, sin = mrope_cos_sin(bucket_positions(L))
b = torch.randn(4, 128, generator=g, dtype=torch.float64) * 30 # bias-dominated k, as in layers 0..3
kw = torch.randn(4, L, 128, generator=g, dtype=torch.float64) # W h, per kv head
T, D = k_bias_tables(b.float(), cos, sin)
rope = lambda t: t * cos.double()[None] + rotate_half(t) * sin.double()[None]
k_full = rope(kw + b[:, None, :])
assert torch.allclose(rope(kw) + T[0].double(), k_full, rtol=0, atol=1e-4)
q = torch.randn(4, L, 128, generator=g, dtype=torch.float64)
causal = torch.ones(L, L, dtype=torch.bool).tril()
sc = lambda k: (q @ k.transpose(1, 2)) / 128 ** 0.5
delta = (sc(rope(kw) + D[0].double()) - sc(k_full)).masked_fill(~causal, float("nan"))
spread = delta.nan_to_num(-1e30).amax(-1) - delta.nan_to_num(1e30).amin(-1) # per row: constant over keys
assert float(spread.max()) < 1e-3 < float(delta.nan_to_num(0).abs().max())
assert D[0].double().mean(1).abs().max() < 1e-4 < T[0].double().mean(1).abs().max()
def _expert_device_form(sd, noise, state, K, Vv, key_mask, num_steps=E.num_steps):
"""fp32 emulation of ExpertTT.forward (32 rows, folded adaLN, windowed self-attn, masked Euler update)."""
from tt_rdt2.reference.expert import ActionExpert
from tt_rdt2.reference.host_fold import deinterleave_wkv
from tt_rdt2.tt.expert import ACT_P, CHUNKS, ROWS, host_mask, host_noise, host_state, state_chunk_weights, time_tables
ref = ActionExpert(sd)
w = ref.w
T = time_tables(ref, num_steps)
Ws = state_chunk_weights(sd)
st = host_state(state)[0, 0]
ss = F.silu(ref.mlp3("state_adaptor.", st[:, :20]) + w["model.state_pos_emb"][0])
S = {k: ss @ v.t() for k, v in Ws.items()}
C = torch.zeros(ROWS, E.hidden)
pos = w["model.x_pos_emb"][0]
C[:24] = pos[:24]
C[24:28] = w["model.register_tokens"][0] + pos[24:]
rowmask = torch.zeros(ROWS, 1)
rowmask[:24] = 1
upd = torch.zeros(ROWS, ACT_P)
upd[:24, :20] = 1.0 / num_steps
mask = host_mask(key_mask)[0] # (1, 32, L)
a = host_noise(noise)[0, 0]
def mrms(x, g, b):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + E.norm_eps) * g + b
for k in range(num_steps):
h = ref.mlp3("act_adaptor.", a[:, :20][None])[0]
x = C + h * rowmask
for i in range(E.depth):
p = f"model.blocks.{i}."
ada = {(kind, xx): T[k][(kind, i, xx)] + S[(kind, i, xx)] for kind in "gbt" for xx in CHUNKS}
hh = mrms(x, ada[("g", "attn")], ada[("b", "attn")])
wk, wv = deinterleave_wkv(w[p + "attn.wkv.weight"])
q = (hh @ w[p + "attn.wq.weight"].t()).view(ROWS, 8, 128).transpose(0, 1)
kk = (hh @ wk.t()).view(ROWS, 4, 128).transpose(0, 1)
vv = (hh @ wv.t()).view(ROWS, 4, 128).transpose(0, 1)
q = rms_norm(q, w[p + "attn.norm_q.weight"], E.norm_eps)
kk = rms_norm(kk, w[p + "attn.norm_k.weight"], E.norm_eps)
kk, vv = kk.repeat_interleave(2, 0), vv.repeat_interleave(2, 0)
o = torch.zeros(8, ROWS, 128)
o[:, :28] = F.scaled_dot_product_attention(q[:, :28], kk[:, :28], vv[:, :28], scale=128 ** -0.5)
o[:, 28:] = F.scaled_dot_product_attention(q[:, 28:], kk[:, 28:], vv[:, 28:], scale=128 ** -0.5)
x = x + ada[("t", "attn")] * (o.transpose(0, 1).reshape(ROWS, -1) @ w[p + "attn.wo.weight"].t())
hh = mrms(x, ada[("g", "cross")], ada[("b", "cross")])
q = (hh @ w[p + "cross_attn.wq.weight"].t()).view(ROWS, 8, 128).transpose(0, 1)
q = rms_norm(q, w[p + "cross_attn.norm_q.weight"], E.norm_eps)
kq = K[i][0].repeat_interleave(2, 0)
vq = Vv[i][0].repeat_interleave(2, 0)
o = F.scaled_dot_product_attention(q, kq, vq, attn_mask=mask, scale=128 ** -0.5)
x = x + ada[("t", "cross")] * (o.transpose(0, 1).reshape(ROWS, -1) @ w[p + "cross_attn.wo.weight"].t())
hh = mrms(x, ada[("g", "mlp")], ada[("b", "mlp")])
f = F.silu(hh @ w[p + "ffn.w1.weight"].t()) * (hh @ w[p + "ffn.w3.weight"].t())
x = x + ada[("t", "mlp")] * (f @ w[p + "ffn.w2.weight"].t())
hh = mrms(x, T[k]["gf"] + S["gf"], T[k]["bf"] + S["bf"])
hh = F.silu(F.linear(hh, w["model.final_layer.ffn.fc1.weight"], w["model.final_layer.ffn.fc1.bias"]))
fc2 = torch.zeros(ACT_P, 4096)
fc2[:20] = w["model.final_layer.ffn.fc2.weight"]
b2 = torch.zeros(ACT_P)
b2[:20] = w["model.final_layer.ffn.fc2.bias"]
v = F.linear(hh, fc2, b2)
a = a + v * upd
return a[:24, :20][None]
@pytest.mark.weights
@pytest.mark.golden
def test_expert_device_form_matches_reference(golden, expert):
from tt_rdt2.reference.weights import load_expert_state_dict
sd = load_expert_state_dict()
for case in ("synth_grad__p0__s1", "real_ur5e__s0"):
d = golden.load(case)
L = 416
n = d["cond.k"].shape[3]
K = torch.zeros(14, 1, 4, L, 128)
Vv = torch.zeros(14, 1, 4, L, 128)
K[:, :, :, :n] = d["cond.k"]
Vv[:, :, :, :n] = d["cond.v"]
K[:, :, :, n:] = 50.0 # junk pad keys: must be masked
km = torch.zeros(L, dtype=torch.bool)
km[:n] = True
got = _expert_device_form(sd, d["in.noise"], d["in.state"], K, Vv, km)
assert pcc(got, d["exp.nsample"]) > 0.999999, case
assert (got - d["exp.nsample"]).abs().max() < 1e-4, case
def test_memory_contract_logic(monkeypatch):
"""VERIFY_MK_r1 R1-F2 (host logic; the device half is in test_tt_device TRACE): once a trace is alive, the allocator
state recorded at the capture must be unchanged at every check; persistent allocations after the seal are refused;
releasing every trace drops the reference state."""
from tt_rdt2.tt.model import RDT2FMTT
m = RDT2FMTT.__new__(RDT2FMTT)
mem = {"dram": 100, "l1": 0}
monkeypatch.setattr(RDT2FMTT, "memory_totals", lambda self: dict(mem))
monkeypatch.setattr(RDT2FMTT, "_persistent_tensors", lambda self: {})
m._persist_addr, m._mem_seal, m.strict_memory, m._sealed = {}, None, True, False
m.traces = {416: None}
assert m._persistent(lambda: "buf") == "buf"
m.check_persistent()
m._sealed = True
with pytest.raises(RuntimeError, match="memory contract"):
m._persistent(lambda: "buf")
m.traces = {416: 7}
m._reseal_memory()
m.check_persistent()
mem["dram"] += 2048 # a buffer allocated after the capture and still alive
with pytest.raises(RuntimeError, match="memory contract"):
m.check_persistent()
m.strict_memory = False
m.check_persistent()
m.strict_memory = True
mem["dram"] -= 2048
m.check_persistent()
m.traces = {416: None}
m._reseal_memory()
assert m._mem_seal is None