"""Incremental decoding with a key/value cache for model.GPT, covering everything the 1B uses: sliding-window attention (per-layer ring buffers, so memory never grows past a layer's window), canon layers (last 3 inputs cached), smear (last token embedding cached), value residual, XSA, attention gates, x0 mix, MoE. Every sequence is one document starting at position 0 (chat prompts are). cache = Cache(model, batch, max_len, device) logits = extend(model, cache, row, ids) # append token ids to one sequence (prompt, tool result) -> [V] logits = step(model, cache, ids, active) # one new token for every row (batched) -> [batch, V]; # rows with active=False are computed but their cache is untouched Matches model.forward to float tolerance (test_kvdecode.py). Run under torch.no_grad() + bf16 autocast on the GPU. """ import torch import torch.nn.functional as F from model import norm class Cache: def __init__(self, model, batch, max_len, device, dtype=torch.bfloat16): cfg = model.cfg self.win = model.layer_windows() # attention window per layer application self.W = [min(w, max_len) for w in self.win] # ring size: a sequence never needs more than max_len slots KV, hd, d = cfg.n_kv_head, cfg.head_dim, cfg.n_embd self.k = [torch.zeros(batch, KV, W, hd, device=device, dtype=dtype) for W in self.W] self.v = [torch.zeros(batch, KV, W, hd, device=device, dtype=dtype) for W in self.W] self.p = [torch.full((batch, W), -1, device=device, dtype=torch.long) for W in self.W] # position in each slot self.ca = [torch.zeros(batch, 3, d, device=device, dtype=dtype) for _ in self.W] # canon inputs t-3..t-1 self.cc = [torch.zeros(batch, 3, d, device=device, dtype=dtype) for _ in self.W] self.prev = torch.zeros(batch, d, device=device, dtype=dtype) # last token embedding self.len = torch.zeros(batch, dtype=torch.long, device=device) self.max_len = max_len self.span = None # step(span=): attend over only the first span ring slots (see step) def reset(self, row): for p in self.p: p[row] = -1 self.len[row] = 0 def _canon(h, w, pos, hist, rows, wr): """Canon layer over new inputs h [R, T, d] with the cached previous 3 inputs of each row.""" R, T, _ = h.shape full = torch.cat([hist[rows].to(h.dtype), h], 1) # [R, 3 + T, d]: inputs at t0-3 .. t0+T-1 out = h + w[0] * h for k in range(1, 4): out = out + (w[k] * full[:, 3 - k:3 - k + T]) * (pos >= k).unsqueeze(-1).to(h.dtype) hist[rows[wr]] = full[wr][:, -3:].to(hist.dtype) return out def _attention(att, x, rotary, pos, v1, cache, j, rows, wr, full): cfg = att.cfg R, T, _ = x.shape q = att.q(x).view(R, T, att.H, att.hd) k = att.k(x).view(R, T, att.KV, att.hd) v = att.v(x).view(R, T, att.KV, att.hd) q, k = norm(q), norm(k) q, k = rotary(q, pos), rotary(k, pos) if cfg.value_residual: if v1 is None: v1 = v elif hasattr(att, "v_lambdas"): v = att.v_lambdas[0] * v + att.v_lambdas[1] * v1 W, win = cache.W[j], cache.win[j] kc, vc, pc = cache.k[j], cache.v[j], cache.p[j] n = min(T, W) if full: # batched single-token step over all rows: write first, then attend over the ring in place (no copies). # Slot pos % W held position pos - W, which is outside the window (W == win; with W < win nothing wraps). r = rows[wr] sl = pos[wr][:, -1] % W kc[r, :, sl] = k[wr][:, -1].to(kc.dtype) vc[r, :, sl] = v[wr][:, -1].to(vc.dtype) pc[r, sl] = pos[wr][:, -1] # span (set by step): no row holds more than span tokens, so slots >= span are empty unless the ring wrapped L = W if cache.span is None or cache.span >= W else cache.span K, V, P = kc[:, :, :L].to(k.dtype), vc[:, :, :L].to(v.dtype), pc[:, :L] else: K = torch.cat([kc[rows].to(k.dtype), k.transpose(1, 2)], 2) # [R, KV, W + T, hd] V = torch.cat([vc[rows].to(v.dtype), v.transpose(1, 2)], 2) P = torch.cat([pc[rows], pos], 1) # [R, W + T] qp, kp = pos[:, :, None], P[:, None, :] mask = (kp >= 0) & (kp <= qp) & (qp - kp < win) # [R, T, keys] y = F.scaled_dot_product_attention(q.transpose(1, 2), K, V, attn_mask=mask[:, None], scale=cfg.attn_scale, enable_gqa=att.H != att.KV).transpose(1, 2) # [R, T, H, hd] if cfg.xsa: vv = v.repeat_interleave(att.H // att.KV, dim=2) if att.H != att.KV else v coef = (y * vv).sum(-1, keepdim=True) / vv.square().sum(-1, keepdim=True).clamp_min(1e-6) y = y - torch.tanh(att.xsa_alpha).view(1, 1, att.H, 1).type_as(y) * coef * vv if cfg.attn_gate: y = y * (2 * torch.sigmoid(att.gate(x))).unsqueeze(-1) # write the newest min(T, W) keys/values into the ring (slot = position mod W) for the rows being advanced if not full and wr.any(): r = rows[wr][:, None].expand(-1, n) sl = pos[wr][:, -n:] % W kc[r, :, sl] = k[wr][:, -n:].to(kc.dtype) vc[r, :, sl] = v[wr][:, -n:].to(vc.dtype) pc[r, sl] = pos[wr][:, -n:] return att.o(y.reshape(R, T, att.H * att.hd)), v1 def _run(model, cache, rows, ids, wr, full=False): """New tokens ids [R, T] for cache rows `rows` -> final hidden states [R, T, d]; advances rows where wr.""" cfg = model.cfg R, T = ids.shape pos = cache.len[rows][:, None] + torch.arange(T, device=ids.device)[None] x = model.wte(ids) if cfg.bf16_resid: x = x.to(torch.bfloat16) raw_last = x[:, -1] if cfg.smear: prev = torch.cat([cache.prev[rows][:, None].to(x.dtype), x[:, :-1]], 1) g = model.smear_lambda * torch.sigmoid(model.smear_gate(x[..., :16])) x = x + (g * (pos >= 1).unsqueeze(-1).to(g.dtype)) * prev x = x0 = norm(x) v1 = None j = 0 for _ in range(cfg.n_loop): for blk in model.blocks: if cfg.x0_mix: x = model.resid_lambdas[j] * x + model.x0_lambdas[j] * x0 h = norm(x) if blk.canon_a is not None: h = _canon(h, blk.canon_a.type_as(h), pos, cache.ca[j], rows, wr) a, v1 = _attention(blk.attn, h, model.rotary, pos, v1, cache, j, rows, wr, full) x = x + a h = norm(x) if blk.canon_c is not None: h = _canon(h, blk.canon_c.type_as(h), pos, cache.cc[j], rows, wr) x = x + blk.mlp(h) j += 1 cache.prev[rows[wr]] = raw_last[wr].to(cache.prev.dtype) cache.len[rows[wr]] += T return norm(x) @torch.no_grad() def extend(model, cache, row, ids): """Append token ids (list) to sequence `row`; returns the logits after the last one [V].""" dev = cache.len.device rows = torch.tensor([row], device=dev) ids = torch.tensor([list(ids)], device=dev) assert int(cache.len[row]) + ids.size(1) <= cache.max_len, "sequence longer than the cache's max_len" h = _run(model, cache, rows, ids, torch.ones(1, dtype=torch.bool, device=dev)) return model.logits(h[0, -1:])[0] @torch.no_grad() def step(model, cache, ids, active=None, span=None): """One token per row: ids [batch] (LongTensor). Rows with active=False are not advanced. Returns logits [batch, V]. span (optional int): an upper bound on every row's length after this step (max over rows of len + 1). Attention then reads only the first span slots of each ring instead of all max_len of them, so a step costs what the rows hold, not what the cache could hold (rl_1b.py's continuous batching: big cache, mostly short rows).""" B = ids.size(0) rows = torch.arange(B, device=ids.device) wr = torch.ones(B, dtype=torch.bool, device=ids.device) if active is None else active cache.span = span try: h = _run(model, cache, rows, ids[:, None], wr, full=True) finally: cache.span = None return model.logits(h[:, 0])