"""Llama-shaped decoder run in CHUNKED PREFILL: `chunk` tokens per call, not one. Every other task in this family is a batch-1 decode step -- GEMV-shaped, bandwidth-bound, latency regime. This one is the other half of a serving stack: a 256-token chunk goes through the whole model in one call, the matmuls become real GEMMs, and the balance flips to compute. The fusion problem is the same shape (one persistent kernel, all layers, no round trips) but everything about the *inside* of it changes: you now have arithmetic intensity to protect rather than bandwidth to conserve. Only the LAST position's logits are returned, which is what a real chunked-prefill scheduler does -- the intermediate positions exist only to fill the KV cache. """ from model import HELPERS_CORE, QUANT_FP8 BODY = r''' def _rope_range(x, cos, sin, pos0): """x: (B, H, T, hd), positions pos0 .. pos0+T-1. Rotation in fp32, cast back.""" T = x.shape[2] c = cos[pos0:pos0 + T].unsqueeze(0).unsqueeze(0) # (1, 1, T, hd/2) s = sin[pos0:pos0 + T].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) 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. The first chunk is written 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, pos) per step, where token_ids is (B, chunk) and the chunk starts at pos.""" g = torch.Generator(device="cuda").manual_seed(seed) C = cfg["chunk"] return [(torch.randint(0, cfg["vocab"], (batch, C), device="cuda", generator=g), base_pos + i * C) for i in range(n)] 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) 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 CHUNK for every sequence in the batch. Appends `chunk` positions into the cache. token_ids: (B, chunk) int64 pos: int, absolute position of token_ids[:, 0] returns: (B, vocab) logits for the LAST position of the chunk only """ W, kv, cfg = handle["W"], handle["kv"], handle["cfg"] cos, sin = handle["cos"], handle["sin"] B, C = token_ids.shape n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"] rep, tot = n_q // n_kv, pos + C # causal mask: query i (absolute position pos+i) sees keys 0 .. pos+i ar = torch.arange(tot, device=token_ids.device) mask = ar.unsqueeze(0) <= (pos + torch.arange(C, device=token_ids.device)).unsqueeze(1) x = W["embed"][token_ids] # (B, C, d) for li, L in enumerate(W["layers"]): h = _rms_norm(x, L["in_norm"], cfg["eps"]) q = (h @ L["q"].T).view(B, C, n_q, hd).transpose(1, 2) k = (h @ L["k"].T).view(B, C, n_kv, hd).transpose(1, 2) v = (h @ L["v"].T).view(B, C, n_kv, hd).transpose(1, 2) q = _rope_range(q, cos, sin, pos) k = _rope_range(k, cos, sin, pos) kc, vc = kv[li] kc[:, :, pos:tot] = k vc[:, :, pos:tot] = v kk = kc[:, :, :tot].repeat_interleave(rep, dim=1) vv = vc[:, :, :tot].repeat_interleave(rep, dim=1) att = F.scaled_dot_product_attention(q, kk, vv, attn_mask=mask) x = x + (att.transpose(1, 2).reshape(B, C, 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[:, -1], W["final_norm"], cfg["eps"]) # LAST position only return x @ W["embed"].T # tied lm_head ''' MODEL_SRC = HELPERS_CORE + QUANT_FP8 + BODY