# SPDX-License-Identifier: Apache-2.0 """Host check (torch, no device) of the layout tricks of the ttnn vision / audio graphs: pooling permutation, permuted 2-D rope, conv1 im2col, f-major conv2 + batched input projection, blocked local attention with the gathered relative bias, the shifted depthwise conv. Compares against the fp32 goldens' per-stage tensors. OMP_NUM_THREADS=2 python -I bundles/embeddinggemma-2/code/tt_embgemma/tests/emu_layouts.py """ from __future__ import annotations import math import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) import numpy as np # noqa: E402 import torch # noqa: E402 import torch.nn.functional as F # noqa: E402 torch.set_num_threads(2) from tt_embgemma import model_spec as S # noqa: E402 from tt_embgemma.preprocess.image import Patches # noqa: E402 from tt_embgemma.reference import model as R # noqa: E402 from tt_embgemma.tests.goldens import MODEL, load # noqa: E402 from tt_embgemma.tt import ttnn_audio as TA # noqa: E402 from tt_embgemma.tt import ttnn_vision as TV # noqa: E402 from tt_embgemma.weights import load_state # noqa: E402 def rel(a, b): a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) return float(np.linalg.norm(a - b) / np.linalg.norm(b)) def rms(x, w=None): return R.rms(x, w) def vision(W): g, gm = load("image_fp32_hooks") key = "i_digit" n = 2304 pix = g[f"{key}.pixel_values"][0][:n] pos = g[f"{key}.image_position_ids"][0][:n] p = Patches(pix, pos, (48, 48), n // 9) host = TV.VisionHost(W) r, xi, yi = host.rows(p) rows = torch.from_numpy(r) tab = W["vision_tower.patch_embedder.position_embedding_table"].float() pe = tab[0][torch.from_numpy(xi.astype(np.int64))] + tab[1][torch.from_numpy(yi.astype(np.int64))] perm = torch.as_tensor(TV.PERM) x = F.linear(rows[:, :768], W["vision_tower.patch_embedder.input_proj.weight"].float()) + pe cos, sin = rows[:, 768:832], rows[:, 832:896] for l in range(S.V_LAYERS): q_ = f"vision_tower.encoder.layers.{l}." Wt = lambda nm: W[q_ + nm].float() # noqa: E731 h = rms(x, Wt("input_layernorm.weight")) def proj(nm, permute): w = Wt(f"self_attn.{nm}.linear.weight") if permute: w = w.view(12, 64, -1)[:, perm].reshape(768, -1) return F.linear(h, w).view(n, 12, 64).transpose(0, 1) q = rms(proj("q_proj", True), Wt("self_attn.q_norm.weight")[perm]) k = rms(proj("k_proj", True), Wt("self_attn.k_norm.weight")[perm]) v = rms(proj("v_proj", False)) q = q * cos + R.rotate_half(q) * sin k = k * cos + R.rotate_half(k) * sin a = torch.softmax(q @ k.transpose(1, 2), -1) @ v a = a.transpose(0, 1).reshape(n, 768) x = x + rms(F.linear(a, Wt("self_attn.o_proj.linear.weight")), Wt("post_attention_layernorm.weight")) h = rms(x, Wt("pre_feedforward_layernorm.weight")) h = F.linear(R.gelu_tanh(F.linear(h, Wt("mlp.gate_proj.linear.weight"))) * F.linear(h, Wt("mlp.up_proj.linear.weight")), Wt("mlp.down_proj.linear.weight")) x = x + rms(h, Wt("post_feedforward_layernorm.weight")) pooled = x.view(n // 9, 9, 768).mean(1) out = F.linear(rms(pooled), W["embed_vision.embedding_projection.weight"].float()) e = rel(out, g[f"{key}.h.embed_vision"]) print("vision emulation vs golden embed_vision rel err", e, flush=True) return e def audio(W): g, gm = load("audio_fp32_hooks") key = "a_ref" feats = g[f"{key}.input_features"][0] mask = g[f"{key}.input_features_mask"][0].astype(bool) T = feats.shape[0] Tb = -(-T // 128) * 128 T1, Tp = Tb // 2, Tb // 4 nv = TA.audio_valid_tokens(mask) p = "audio_tower.subsample_conv_projection." cols = torch.from_numpy(TA.im2col_conv1(feats, mask, Tb)) w1 = torch.cat([W[p + "layer0.conv.weight"].float().reshape(128, 9).t(), torch.zeros(23, 128)], 0) h = F.relu(F.layer_norm(cols @ w1, (128,), W[p + "layer0.norm.weight"].float(), None, S.EPS)) # [64*T1, 128] img = h.view(64, T1, 128).permute(2, 0, 1)[None] # NCHW, H=f, W=t y = F.conv2d(img, W[p + "layer1.conv.weight"].float().transpose(2, 3), stride=2, padding=1) # [1, 32, 32, Tp] y = y[0].permute(1, 2, 0).reshape(32 * Tp, 32) # rows f*Tp + t y = F.relu(F.layer_norm(y, (32,), W[p + "layer1.norm.weight"].float(), None, S.EPS)) wi = W[p + "input_proj_linear.weight"].float().t().reshape(32, 32, 1024) x = torch.einsum("ftc,fco->to", y.view(32, Tp, 32), wi) gx = g[f"{key}.h.at.subsample"][0] e_sub = rel(x[:gx.shape[0]], gx) print("audio subsample emulation rel err", e_sub, flush=True) nblk, idx, band, shifts = TA.static_tensors(Tp) am = torch.from_numpy(TA.attn_mask(nv, Tp))[0] # [nblk, 32, 64] rp = TA.AudioWeights._rel_pos() H, D = 8, 128 def ctx(t): # [h, Tp, D] -> [h, nblk, 64, D] hh_ = t.shape[0] prev = torch.cat([torch.zeros(hh_, 32, t.shape[-1]), t[:, :-32]], 1) return torch.cat([prev.reshape(hh_, nblk, 32, -1), t.reshape(hh_, nblk, 32, -1)], 2) def clip_lin(nm, t): return R._clip_lin(W, nm, t) for l in range(S.A_LAYERS): q_ = f"audio_tower.layers.{l}." x = R.audio_ffw(W, q_ + "feed_forward1.", x) hh = rms(x, W[q_ + "norm_pre_attn.weight"].float()) sa = q_ + "self_attn." q = clip_lin(sa + "q_proj", hh) * ((D ** -0.5) / math.log(2)) * F.softplus(W[sa + "per_dim_scale"].float()).repeat(H) k = clip_lin(sa + "k_proj", hh) * (math.log(1 + math.e) / math.log(2)) v = clip_lin(sa + "v_proj", hh) q, k, v = (t.view(Tp, H, D).transpose(0, 1) for t in (q, k, v)) Rr = F.linear(rp, W[sa + "relative_k_proj.weight"].float()).view(13, H, D) Rt = torch.zeros(H, D, 64) Rt[:, :, :13] = Rr.permute(1, 2, 0) qr = (q @ Rt).view(H, nblk, 32, 64) bias = torch.gather(qr, -1, torch.from_numpy(idx)[None, None].expand(H, nblk, 32, 64)) s = q.reshape(H, nblk, 32, D) @ ctx(k).transpose(-1, -2) + bias s = torch.tanh(s / 50.0) * 50.0 + am[None] o = torch.softmax(s, -1) @ ctx(v) o = o.reshape(H, Tp, D).transpose(0, 1).reshape(Tp, H * D) x = x + rms(clip_lin(sa + "post", o), W[q_ + "norm_post_attn.weight"].float()) # lconv lc = q_ + "lconv1d." r = x hh = rms(x, W[lc + "pre_layer_norm.weight"].float()) hh = F.glu(clip_lin(lc + "linear_start", hh), dim=-1) dw = W[lc + "depthwise_conv1d.weight"].float().reshape(1024, 5) c = ctx(hh[None])[0] # [nblk, 64, C] stk = torch.cat([c * dw[:, i] for i in range(5)], 1) # [nblk, 320, C] sh = torch.from_numpy(np.concatenate(list(shifts), axis=1)) # [32, 320] yy = (sh @ stk).reshape(Tp, 1024) yy = F.silu(rms(yy, W[lc + "conv_norm.weight"].float())) x = r + clip_lin(lc + "linear_end", yy) x = R.audio_ffw(W, q_ + "feed_forward2.", x) x = rms(x, W[q_ + "norm_out.weight"].float()) out = F.linear(x, W["audio_tower.output_proj.weight"].float(), W["audio_tower.output_proj.bias"].float()) go = g[f"{key}.h.at.output_proj"][0] e = rel(out[:nv], go[:nv]) print("audio tower emulation rel err (valid rows)", e, nv, flush=True) return e_sub, e def main(): W = {k: v.float() for k, v in load_state(MODEL, ("vision", "audio")).items()} ev = 0.0 if os.environ.get("EMU_SKIP_VISION") else vision(W) es, ea = audio(W) ok = ev < 1e-4 and es < 1e-4 and ea < 1e-4 print("EMU", "PASS" if ok else "FAIL") if __name__ == "__main__": main()