# SPDX-License-Identifier: Apache-2.0 """Host tests of the DEC-MoE megakernel's host side (no device, no ttnn): geometry, stream sizes, the fast packer, and an fp32 emulation of the kernel's per-core decomposition (arena bytes -> per-core streams in consumption order) against a direct computation of the same (random) decoder layers 0 (dense) and 1 (MoE).""" from __future__ import annotations import os import sys import numpy as np import pytest import torch HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(os.path.dirname(HERE))) from tt_dsocr.tt.mk_moe import arena as A # noqa: E402 from tt_dsocr.tt.mk_moe import formats as F # noqa: E402 from tt_dsocr.tt.mk_moe import geometry as G # noqa: E402 OPT0 = [(0, 0), (0, 3), (0, 6), (0, 9), (7, 0), (7, 3), (7, 6), (7, 9)] OPT1 = [(1, 1), (1, 4), (1, 7), (1, 8), (8, 1), (8, 4), (8, 7), (8, 8)] def geo(attk=4): return G.build(12, 10, OPT0, OPT1, attk=attk) def test_geometry(): g = geo() assert len(g.mm) == 32 and len(g.att) == 40 and len(g.rt) == 2 assert len(set(g.active)) == g.n_active() assert sum(m.xn for m in g.mm) == 40 offs = sorted((m.xoff, m.xn) for m in g.mm) pos = 0 for o, n in offs: assert o == pos pos += n assert sum(m.nsc for m in g.mm) == 56 and sum(m.rcol for m in g.mm) == 28 assert [m.hk for m in g.mm].count(G.HK_NONE) == 2 for m in g.mm: assert G.a_tiles(m) % G.PACKET_TILES["A"] == 0 assert G.m0_tiles(m) % G.PACKET_TILES["M"] == 0 for v in G.moe_tiles(m).values(): assert v % G.PACKET_TILES["M"] == 0 assert G.h_tiles() % G.PACKET_TILES["H"] == 0 and G.HC == 127 for fa, fm, fh in (("bfp8", "bfp8", "bf16"), ("bf16", "bf16", "bf16"), ("bfp8", "bfp8", "bfp8")): assert G.cb_total(fa, fm, 4, fh) <= G.L1_BUDGET, (fa, fm, fh, G.cb_total(fa, fm, 4, fh)) # f indices: a permutation of 0..223 idx = [G.f_index_shared(t) for t in range(56)] + [G.f_index_routed(k, t) for k in range(6) for t in range(28)] assert sorted(idx) == list(range(224)) def test_every_kernel_cb_is_configured(): """Every CB_* the kernels use exists in the CB table (an unconfigured CB hangs the TRISC: FAULTS #2).""" import re src = "".join(open(os.path.join(G.KDIR, f)).read() for f in ("md_brisc.cpp", "md_ncrisc.cpp", "md_trisc.cpp", "md_dm.hpp")) used = set(re.findall(r"\b(CB_[A-Z0-9]+)\b", src)) for fa, fm, fh in (("bfp8", "bfp8", "bf16"), ("bfp8", "bfp8", "bfp8"), ("bf16", "bf16", "bf16")): tab = {cid for cb in G.cb_table(fa, fm, 4, fh) for cid, *_ in cb.ids} missing = sorted(n for n in used if getattr(G, n) not in tab) assert not missing, (fa, fm, fh, missing) @pytest.mark.parametrize("fmt", ["bfp8", "bf16"]) def test_pack_fast(fmt): torch.manual_seed(0) t = torch.randn(300, 1024) * torch.logspace(-3, 2, 300)[:, None] t[5, :16] = 0 t[7, 3] = 1e-30 a = A.pack_fast(t, fmt) b = F.pack_tiles(t, fmt) assert np.array_equal(a, b) class FakeW: """Random decoder weights with the checkpoint names (2 layers: dense + MoE).""" def __init__(self, seed=0): g = torch.Generator().manual_seed(seed) r = lambda *s: torch.randn(*s, generator=g) * 0.02 # noqa: E731 d = {} for l in range(2): p = f"model.layers.{l}." d[p + "input_layernorm.weight"] = 1 + r(1280) * 10 d[p + "post_attention_layernorm.weight"] = 1 + r(1280) * 10 for n in ("q", "k", "v", "o"): d[p + f"self_attn.{n}_proj.weight"] = r(1280, 1280) p = "model.layers.0.mlp." d[p + "gate_proj.weight"] = r(6848, 1280) d[p + "up_proj.weight"] = r(6848, 1280) d[p + "down_proj.weight"] = r(1280, 6848) p = "model.layers.1.mlp." d[p + "gate.weight"] = r(64, 1280) * 10 for n in ("gate", "up"): d[p + f"shared_experts.{n}_proj.weight"] = r(1792, 1280) d[p + "shared_experts.down_proj.weight"] = r(1280, 1792) for e in range(64): d[p + f"experts.{e}.gate_proj.weight"] = r(896, 1280) d[p + f"experts.{e}.up_proj.weight"] = r(896, 1280) d[p + f"experts.{e}.down_proj.weight"] = r(1280, 896) d["model.norm.weight"] = 1 + r(1280) d["lm_head.weight"] = r(129280, 1280) self.d = d def get(self, k, cache=True): return self.d[k] def read_stream(pages, bank, off, ntiles, fmt): tb = G.TILE_BYTES[fmt] nb = 8 view = pages.reshape(-1, nb, A.PAGE) flat = view[:, bank, :].reshape(-1) return F.unpack_tiles(flat[off:off + ntiles * tb].reshape(ntiles, tb), fmt) def untile_cols(tiles, kt, ncol): """Column sticks (for c: K tiles) -> [K, ncol*32] fp32.""" out = torch.zeros(kt * 32, ncol * 32) for c in range(ncol): for k in range(kt): out[k * 32:(k + 1) * 32, c * 32:(c + 1) * 32] = tiles[c * kt + k].reshape(2, 2, 16, 16).permute( 0, 2, 1, 3).reshape(32, 32) return out def untile_kmajor(tiles, kt, ncol): out = torch.zeros(kt * 32, ncol * 32) for k in range(kt): for c in range(ncol): out[k * 32:(k + 1) * 32, c * 32:(c + 1) * 32] = tiles[k * ncol + c].reshape(2, 2, 16, 16).permute( 0, 2, 1, 3).reshape(32, 32) return out def test_emulated_mlp_layers(): """The kernel's MLP decomposition (layer 0 dense, layer 1 MoE with a given routing) from the packed bf16 arena == the direct fp32 computation with bf16-rounded weights (gammas folded).""" W = FakeW() g = geo() recipe = {"attn": "bf16", "mlp": "bf16", "head": "bf16"} pages, offs, rto = A.build_arena(W, g, recipe, n_layers=2, cache=False, log=lambda s: None) torch.manual_seed(1) h = torch.randn(1280) # normalised input (rstd folded out: x_hat) bf = lambda t: t.to(torch.bfloat16).float() # noqa: E731 # ---- layer 0 (dense) p = "model.layers.0." g2 = W.get(p + "post_attention_layernorm.weight") wg, wu, wd = (W.get(p + f"mlp.{n}_proj.weight") for n in ("gate", "up", "down")) ref0 = bf(wd) @ (torch.nn.functional.silu(bf(wg * g2) @ h) * (bf(wu * g2) @ h)) f = torch.zeros(224 * 32) tb = G.TILE_BYTES["bf16"] for m in g.mm: base = offs[m.w][1] t = read_stream(pages, m.bank, base, G.m0_tiles(m), "bf16") for j in range(7): gate = untile_cols(t[j * 80:j * 80 + 40], 40, 1)[:, :] up = untile_cols(t[j * 80 + 40:j * 80 + 80], 40, 1) col = 7 * m.w + j f[col * 32:(col + 1) * 32] = torch.nn.functional.silu(h @ gate) * (h @ up) y = torch.zeros(1280) for m in g.mm: base = offs[m.w][1] + 560 * tb t = read_stream(pages, m.bank, base, m.xn * G.ITK0, "bf16") wdm = untile_kmajor(t, G.ITK0, m.xn) y[m.xoff * 32:(m.xoff + m.xn) * 32] = f[:G.ITK0 * 32] @ wdm assert torch.allclose(y, ref0, atol=1e-4, rtol=1e-3), float((y - ref0).abs().max()) # ---- layer 1 (MoE) with routing ids / weights p = "model.layers.1.mlp." g2 = W.get("model.layers.1.post_attention_layernorm.weight") ids = [5, 17, 63, 0, 40, 33] wts = torch.tensor([0.3, 0.2, 0.1, 0.05, 0.04, 0.01]) sw = lambda pre, x: bf(W.get(pre + "down_proj.weight")) @ ( # noqa: E731 torch.nn.functional.silu(bf(W.get(pre + "gate_proj.weight") * g2) @ x) * (bf(W.get(pre + "up_proj.weight") * g2) @ x)) ref1 = sw(p + "shared_experts.", h) for e, wt in zip(ids, wts): ref1 = ref1 + wt * sw(p + f"experts.{e}.", h) f = torch.zeros(224 * 32) for m in g.mm: base = offs[m.w][1] + G.m0_tiles(m) * tb mt = G.moe_tiles(m) cols = [] t = read_stream(pages, m.bank, base, mt["sgu"], "bf16") for j in range(m.nsc): cols.append((torch.nn.functional.silu(h @ untile_cols(t[j * 80:j * 80 + 40], 40, 1)) * (h @ untile_cols(t[j * 80 + 40:j * 80 + 80], 40, 1)))) if m.rcol: for k, e in enumerate(ids): t = read_stream(pages, m.bank, base + (mt["sgu"] + e * mt["egu"]) * tb, mt["egu"], "bf16") v = torch.nn.functional.silu(h @ untile_cols(t[:40], 40, 1)) * (h @ untile_cols(t[40:], 40, 1)) f[G.f_index_routed(k, m.w) * 32:(G.f_index_routed(k, m.w) + 1) * 32] = v * wts[k] for j, v in enumerate(cols): ti = G.f_index_shared(m.sc0 + j) f[ti * 32:(ti + 1) * 32] = v y = torch.zeros(1280) for m in g.mm: base = offs[m.w][1] + G.m0_tiles(m) * tb mt = G.moe_tiles(m) sd0 = base + (mt["sgu"] + 64 * mt["egu"]) * tb t = read_stream(pages, m.bank, sd0, mt["sdn"], "bf16") wsd = untile_kmajor(t, 56, m.xn) fs = torch.cat([f[G.f_index_shared(tt) * 32:(G.f_index_shared(tt) + 1) * 32] for tt in range(56)]) acc = fs @ wsd for k, e in enumerate(ids): t = read_stream(pages, m.bank, sd0 + (mt["sdn"] + e * mt["edn"]) * tb, mt["edn"], "bf16") wde = untile_kmajor(t, 28, m.xn) fr = torch.cat([f[G.f_index_routed(k, tt) * 32:(G.f_index_routed(k, tt) + 1) * 32] for tt in range(28)]) acc = acc + fr @ wde y[m.xoff * 32:(m.xoff + m.xn) * 32] = acc assert torch.allclose(y, ref1, atol=1e-4, rtol=1e-3), float((y - ref1).abs().max()) # router stream: column tile r of diag(g2) W_gate^T wr = bf(W.get(p + "gate.weight").t() * g2[:, None]) for r in range(2): t = read_stream(pages, g.rt_bank[r], rto[r], 40, "bf16") assert torch.equal(untile_cols(t, 40, 1), wr[:, 32 * r:32 * r + 32])