| """Shared decoder-model reference for the megakernel family. |
| |
| `HELPERS` (RMSNorm, RoPE, dequant) is reused verbatim by every architecture variant in |
| `_mega_factory/models/`, so each generated `reference.py` is self-contained and readable. |
| |
| This source is embedded verbatim into both `environment/reference.py` (what the agent reads) and |
| `tests/verify_env.py` (the grader's private copy), so editing the former cannot affect grading. |
| |
| Everything here is the numerical SPECIFICATION: correct, deliberately unfused, and slow. Speed of this |
| file has no bearing on the score, which is an absolute throughput number. |
| |
| Weight init is `1/sqrt(fan_in)` scaled ON PURPOSE. Unscaled randn diverges over depth and turns the |
| logit comparison into noise-vs-noise (measured: activation RMS stays 1.13 -> 4.65 over 16 layers). |
| """ |
|
|
| HELPERS_CORE = r''' |
| def _rms_norm(x, w, eps): |
| return F.rms_norm(x, (x.shape[-1],), w, eps) |
| |
| |
| def _rope_cache(cfg, maxlen, device): |
| hd, theta = cfg["hd"], cfg["theta"] |
| inv = 1.0 / (theta ** (torch.arange(0, hd, 2, device=device).float() / hd)) |
| f = torch.outer(torch.arange(maxlen, device=device).float(), inv) |
| return torch.cos(f), torch.sin(f) |
| |
| |
| def _apply_rope(x, cos, sin, pos): |
| """x: (B, H, T, hd). Rotation is done in fp32 (cos/sin are fp32) then cast back.""" |
| c, s = cos[pos].unsqueeze(0).unsqueeze(0), sin[pos].unsqueeze(0).unsqueeze(0) |
| xf = x.float() |
| x1, x2 = xf[..., ::2], xf[..., 1::2] |
| return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1).flatten(-2).to(x.dtype) |
| ''' |
|
|
| QUANT_FP8 = r''' |
| |
| def _quantise(w, dt): |
| """Weights are shipped ALREADY QUANTISED. Quantisation error is part of the INPUT, not of the |
| kernel: with an fp32 fixture a correct fp8 kernel disagrees with the reference on 17% of steps |
| (measured relerr 0.137 vs 0.014 when pre-quantised).""" |
| if dt == "bf16": |
| return w.to(torch.bfloat16) |
| if dt == "fp8": # e4m3, per-output-channel bf16 scale |
| amax = w.abs().amax(dim=-1, keepdim=True).clamp(min=1e-6) |
| scale = amax / 448.0 |
| return (w / scale).clamp(-448, 448).to(torch.float8_e4m3fn), scale.to(torch.bfloat16) |
| raise ValueError(dt) |
| |
| |
| def _deq(w): |
| """(fp8_tensor, per-channel scale) -> bf16. Plain bf16 weights pass through.""" |
| if isinstance(w, tuple): |
| q, s = w |
| return (q.float() * s.float()).to(torch.bfloat16) |
| return w |
| ''' |
|
|
| HELPERS = HELPERS_CORE + QUANT_FP8 |
|
|
| LLAMA_BODY = r''' |
| def make_weights(cfg, seed=0, device="cuda"): |
| """Deterministic 1/sqrt(fan_in)-scaled weights. No checkpoint is shipped or downloaded.""" |
| 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"] |
| dt = cfg["wdtype"] |
| |
| def rnd(*shape, fan_in): |
| w = torch.randn(*shape, device=device, dtype=torch.float32, generator=g) / (fan_in ** 0.5) |
| return _quantise(w, 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), |
| gate=rnd(ffn, d, fan_in=d), up=rnd(ffn, d, fan_in=d), down=rnd(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 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. |
| |
| Dequantisation happens ONCE here rather than per step. That is not just a speed choice: dequantising |
| a 128k-row embedding inside every step allocates ~525 MB per call, which perturbs the caching |
| allocator enough that cuBLAS picks different GEMV algorithms run-to-run and two bit-identical |
| implementations drift apart by ~1.4e-2. Hoisting it makes the reference exactly reproducible. |
| """ |
| cos, sin = _rope_cache(cfg, max_seq_len, weights["final_norm"].device) |
| W = {"embed": _deq(weights["embed"]), "final_norm": weights["final_norm"], |
| "layers": [{k: (v if k.endswith("norm") 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, 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 |
| returns: (B, vocab) logits |
| """ |
| W, kv, cfg = handle["W"], handle["kv"], handle["cfg"] |
| cos, sin = handle["cos"], handle["sin"] |
| B = token_ids.shape[0] |
| d, n_q, n_kv, hd = cfg["d"], cfg["n_q"], cfg["n_kv"], cfg["hd"] |
| 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) |
| h = _rms_norm(x, L["post_norm"], cfg["eps"]) |
| x = x + ((F.silu(h @ L["gate"].T) * (h @ L["up"].T)) @ L["down"].T) |
| x = _rms_norm(x, W["final_norm"], cfg["eps"]) |
| return x @ W["embed"].T # tied lm_head |
| ''' |
|
|
| MODEL_SRC = HELPERS + LLAMA_BODY |
|
|