"""Qwen3-MoE-shaped decoder: GQA attention + a top-k routed sparse MLP. Every layer stores `n_experts` expert MLPs but reads only `top_k` of them per token, so the model holds ~5.4 B parameters while touching ~1.2 B per decode step. That gap is the point: the megakernel has to discover its weight addresses at run time instead of streaming a static sequence of matrices. WHY THE DISPATCH PLAN IS AN INPUT --------------------------------- The *set* of experts is given to `decode_step` as a plan tensor; the *gating weights* are still computed by a real router GEMV over the layer's hidden state. That split is deliberate and it is a measured decision, not a simplification for convenience. `argmax`-based expert selection cannot be graded. Two correct implementations of this model differ in the hidden state by ~1e-2 (bf16 vs fp32 residual), the router logits inherit that difference, and the top-k membership then flips discretely. Measured end-to-end relative error between the shipped bf16 reference and an equally-correct fp32 implementation, purely from routing flips: flat random router (sigma 1) relerr 1.27 peaked router (sigma 3) relerr 0.19 peaked router (sigma 5) relerr 0.31 against ~0.03 for the same model with a dense MLP. There is no tolerance that both accepts an honest fp32 kernel and rejects "only use half the experts". Selection is therefore exact integer data -- which is also what an expert-parallel serving stack actually hands its expert kernels, since dispatch is planned before the expert GEMMs are launched. """ from model import HELPERS BODY = r''' def make_weights(cfg, seed=0, device="cuda"): """Deterministic 1/sqrt(fan_in)-scaled weights. Experts are STACKED: one (E, ...) tensor per projection per layer, which is how a serving stack lays them out for a grouped GEMM.""" g = torch.Generator(device=device).manual_seed(seed) d, ffn, n_q, n_kv, hd = cfg["d"], cfg["ffn"], cfg["n_q"], cfg["n_kv"], cfg["hd"] E, dt = cfg["n_experts"], cfg["wdtype"] def rnd(*shape, fan_in, dtype=None): w = torch.randn(*shape, device=device, dtype=torch.float32, generator=g) / (fan_in ** 0.5) return _quantise(w, dtype or dt) ones = lambda: torch.ones(d, device=device, dtype=torch.bfloat16) W = {"embed": rnd(cfg["vocab"], d, fan_in=d), "final_norm": ones(), "layers": []} for _ in range(cfg["layers"]): W["layers"].append(dict( in_norm=ones(), post_norm=ones(), q=rnd(n_q * hd, d, fan_in=d), k=rnd(n_kv * hd, d, fan_in=d), v=rnd(n_kv * hd, d, fan_in=d), o=rnd(d, n_q * hd, fan_in=n_q * hd), # the router stays bf16: it is (E, d), it is read in full every step, and it is tiny. router=rnd(E, d, fan_in=d, dtype="bf16"), gate=rnd(E, ffn, d, fan_in=d), up=rnd(E, ffn, d, fan_in=d), down=rnd(E, d, ffn, fan_in=ffn))) return W def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"): """KV cache already holding `prefill_len` tokens. Decode starts at pos = prefill_len.""" g = torch.Generator(device=device).manual_seed(seed + 777) kv = [] for _ in range(cfg["layers"]): k = torch.zeros(batch, cfg["n_kv"], max_seq, cfg["hd"], device=device, dtype=torch.bfloat16) v = torch.zeros_like(k) k[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device, dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5 v[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device, dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5 kv.append((k, v)) return kv def make_step_args(cfg, batch, base_pos, seed, n): """(token_ids, plan, pos) per step. `plan` is (B, layers, top_k) int32: for every sequence and every layer, the DISTINCT expert ids this token is dispatched to. It is the routing decision, delivered as data.""" g = torch.Generator(device="cuda").manual_seed(seed) E, L, K = cfg["n_experts"], cfg["layers"], cfg["top_k"] out = [] for i in range(n): tok = torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g) # distinct experts per (sequence, layer): argsort of a random key, take the first K key = torch.rand(batch, L, E, device="cuda", generator=g) plan = key.argsort(dim=-1)[:, :, :K].to(torch.int32).contiguous() out.append((tok, plan, base_pos + i)) return out def build_model(weights, kv_cache, cfg, max_seq_len): """UNTIMED setup. Returns whatever handle you like; the grader only passes it back to decode_step.""" cos, sin = _rope_cache(cfg, max_seq_len, weights["final_norm"].device) keep = ("in_norm", "post_norm", "router") W = {"embed": _deq(weights["embed"]), "final_norm": weights["final_norm"], "layers": [{k: (v if k in keep else _deq(v)) for k, v in L.items()} for L in weights["layers"]]} return {"W": W, "kv": kv_cache, "cfg": cfg, "cos": cos, "sin": sin} @torch.no_grad() def decode_step(handle, token_ids, plan, pos): """One decode step for every sequence in the batch. Appends this position's K/V into the cache. token_ids: (B,) int64 pos: int, the absolute position being written plan: (B, layers, top_k) int32, the experts this token is dispatched to returns: (B, vocab) logits """ W, kv, cfg = handle["W"], handle["kv"], handle["cfg"] cos, sin = handle["cos"], handle["sin"] B = token_ids.shape[0] n_q, n_kv, hd, top_k = cfg["n_q"], cfg["n_kv"], cfg["hd"], cfg["top_k"] rep = n_q // n_kv x = W["embed"][token_ids] for li, L in enumerate(W["layers"]): h = _rms_norm(x, L["in_norm"], cfg["eps"]) q = (h @ L["q"].T).view(B, n_q, 1, hd) k = (h @ L["k"].T).view(B, n_kv, 1, hd) v = (h @ L["v"].T).view(B, n_kv, 1, hd) q = _apply_rope(q, cos, sin, pos) k = _apply_rope(k, cos, sin, pos) kc, vc = kv[li] kc[:, :, pos:pos + 1] = k vc[:, :, pos:pos + 1] = v kk = kc[:, :, :pos + 1].repeat_interleave(rep, dim=1) vv = vc[:, :, :pos + 1].repeat_interleave(rep, dim=1) att = F.scaled_dot_product_attention(q, kk, vv) x = x + (att.reshape(B, n_q * hd) @ L["o"].T) # ---- routed sparse MLP ------------------------------------------------------------------- h = _rms_norm(x, L["post_norm"], cfg["eps"]) idx = plan[:, li].long() # (B, top_k) expert ids rl = (h.float() @ L["router"].T.float()) # (B, E) router logits, fp32 gw = torch.softmax(torch.gather(rl, 1, idx), dim=-1) # softmax over the DISPATCHED experts y = torch.zeros_like(x, dtype=torch.float32) for b in range(B): for j in range(top_k): e = int(idx[b, j]) hb = h[b:b + 1] g_e = F.silu(hb @ L["gate"][e].T) * (hb @ L["up"][e].T) y[b:b + 1] += gw[b, j] * (g_e @ L["down"][e].T).float() x = x + y.to(x.dtype) x = _rms_norm(x, W["final_norm"], cfg["eps"]) return x @ W["embed"].T # tied lm_head ''' MODEL_SRC = HELPERS + BODY