"""Perceiver AR (MrCogito) for πŸ€— Transformers: the modeling code of a Hub release. Entry point: `PerceiverARForCausalLM` (AutoModelForCausalLM; nn/perceiver_ar_hub.py at the end of this file). The source modules follow in import order, with their `nn.` imports resolved inside this file. Generated by scripts/export_hub_model.py from https://github.com/ksopyla/MrCogito at commit 2e6b9573c8fb, from nn/exact_read.py, nn/latent_memory.py, nn/concept_memory.py, nn/perceiver_ar_lm.py, nn/incremental.py, nn/perceiver_ar_hub.py. Do not edit: change the source and export again. Engineering spec: docs/engineering_specs/hub_from_pretrained_loading.md. """ from __future__ import annotations import copy import dataclasses import logging import math import os import torch import torch.nn as nn import torch.nn.functional as F from contextlib import contextmanager from dataclasses import dataclass from functools import partial from torch.utils.checkpoint import checkpoint as torch_checkpoint from transformers import GenerationMixin, PreTrainedModel, PretrainedConfig from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast from types import SimpleNamespace from typing import Callable, Optional, Union from .configuration_perceiver_ar import PerceiverARConfig # ============================================================================================================== # nn/exact_read.py # ============================================================================================================== # E33p β€” the exact read: each query opens the raw keys of the groups it chose (notes, pages, LSA buckets). # # Spec: docs/experiments_specs/ahead/E33p_note_indexed_exact_read.md Β· plan: E33p_plan.md (Β§0, Β§3). # # A *group* is a set of earlier raw tokens: a note's member tokens (the page tokens whose largest writer assignment is # that note), a page's picked tokens, or an LSA bucket. Groups live in *spans* (a page, an LSA block of keys); a token # belongs to at most one group per span. Spans may overlap (pages, stride < window): the spans are split into `layers` # whose members never overlap, and each layer gives every token one code (βˆ’1 = not a member there). # # Per query i, without gradient: rank the candidate groups, take the best m, fill `cap` places best group first, each # group's members oldest first, counting only members in [doc_start(i), i βˆ’ raw_window] (the rest are in i's window or # in another document; sinks are never members). The result is one table T[b, i, g] = the places used before group g # (`cap` when g is not chosen). Raw token j, a member of g at rank ord(j) (members of g in [doc_start(j), j)), is # opened for i iff i βˆ’ j β‰₯ raw_window and T[i, g] + ord(j) < cap. A token in two chosen groups opens once (an OR), # counted in both (≀ cap distinct tokens per query). The attention kernel reads T through one 2-D gather per layer plus # 1-D lookups along the key axis; `dense_open` is the same rule as a dense mask (SDPA, tests, probes). # # Shapes (s30, 16k row): S = 16,384; notes G = 2,720 (85 pages Γ— 32), pages G = 85, LSA buckets G = 2,048 # (32 closed 512-key blocks Γ— 64); T [B, S, G] int16. ORD_BITS = 9 # code = gid Β· 512 + ord (ord < 512: members of one group within a ≀ 512-token span) ORD_MOD = 1 << ORD_BITS SINK = -2 # code of an LSA sink token (layer 0) _BIG = 1 << 40 @dataclass class GroupIndex: """Groups of raw keys for one forward (or one loop round, for LSA). G = n_s Β· per_span groups, gid = s Β· per_span + l.""" span_start: torch.Tensor # [n_s] long β€” first position of each span span_len: int # L per_span: int # groups per span prefix: torch.Tensor # [B, n_s, L + 1, per_span] int32 β€” members of group (s, l) at span offsets < o codes: torch.Tensor # [n_layers, B, S] int32 β€” gid Β· 512 + ord, βˆ’1 not a member, βˆ’2 sink (layer 0) doc_start: torch.Tensor # [B, S] long β€” first position of each token's document g_close: torch.Tensor # [B, G] long β€” the group is visible to queries i β‰₯ g_close (βˆ’1 = never) g_doc: torch.Tensor # [B, G] long β€” its document (βˆ’1 = none); `any_doc` groups are visible across documents g_minpos: torch.Tensor # [B, G] long β€” oldest member (β‰₯ 2⁴⁰ when it has none) g_kb: torch.Tensor # [B, G, 2] long β€” first and last 128-key block holding a member (lo > hi when none) any_doc: bool = False @property def n_groups(self) -> int: return int(self.g_close.shape[1]) def span_layers(starts: list[int], length: int) -> list[int]: """Assign spans to layers so that spans of one layer never overlap (greedy, in start order). Static (Python).""" ends: list[int] = [] out = [] for s in starts: for li, e in enumerate(ends): if e <= s: ends[li] = s + length out.append(li) break else: ends.append(s + length) out.append(len(ends) - 1) return out def doc_starts(doc: torch.Tensor) -> torch.Tensor: """[B, S] long: the first position of each token's document (contiguous documents; βˆ’1 ids count as documents).""" B, S = doc.shape idx = torch.arange(S, device=doc.device)[None].expand(B, S) new = torch.ones_like(doc, dtype=torch.bool) new[:, 1:] = doc[:, 1:] != doc[:, :-1] return torch.cummax(torch.where(new, idx, torch.zeros_like(idx)), dim=1).values def groups_from_spans(member: torch.Tensor, span_start: list[int], *, S: int, per_span: int, doc_start: torch.Tensor, g_close: torch.Tensor, g_doc: torch.Tensor, any_doc: bool = False, sink: Optional[torch.Tensor] = None, block: int = 128) -> GroupIndex: """Build a GroupIndex from each span's member labels. member [B, n_s, L] long: the group (0 … per_span βˆ’ 1) of the token at offset o of span s, βˆ’1 = not a member (unpicked, out of range, sink); positions span_start[s] + o must be < S where member β‰₯ 0. g_close / g_doc [B, G]: visibility of each group (set by the caller). sink [B, S] bool: LSA sinks (code βˆ’2).""" B, n_s, L = member.shape dev = member.device st = torch.tensor(span_start, device=dev, dtype=torch.long) pos = st[:, None] + torch.arange(L, device=dev)[None] # [n_s, L] valid = (member >= 0) & (pos < S)[None] ml = torch.where(valid, member, torch.zeros_like(member)) onehot = (ml[..., None] == torch.arange(per_span, device=dev)) & valid[..., None] # [B, n_s, L, K] prefix = F.pad(onehot.to(torch.int32).cumsum(2), (0, 0, 1, 0)) # [B, n_s, L + 1, K] # ord: members of the token's group in [doc_start(token), token) pos_c = pos.clamp(max=S - 1) before = prefix[:, :, :L].gather(-1, ml[..., None]).squeeze(-1) # [B, n_s, L] ds = doc_start[:, pos_c.reshape(-1)].view(B, n_s, L) o_ds = (ds - st[None, :, None]).clamp(0, L) at_ds = prefix.gather(2, o_ds[..., None].expand(B, n_s, L, per_span)).gather(-1, ml[..., None]).squeeze(-1) ordv = (before - at_ds).clamp(min=0) gid = torch.arange(n_s, device=dev)[None, :, None] * per_span + ml code = torch.where(valid, gid.to(torch.int32) * ORD_MOD + ordv.to(torch.int32), torch.full_like(ordv, -1, dtype=torch.int32)) layers = span_layers(list(span_start), L) n_layers = max(layers) + 1 if layers else 1 codes = torch.full((n_layers, B, S + 1), -1, dtype=torch.int32, device=dev) for li in range(n_layers): sel_l = [s for s, x in enumerate(layers) if x == li] # static: no host sync if not sel_l: continue sel = torch.tensor(sel_l, device=dev) p = pos[sel].reshape(-1) c = code[:, sel].reshape(B, -1) v = valid[:, sel].reshape(B, -1) dest = torch.where(v, p[None].expand(B, -1), torch.full_like(c, S, dtype=torch.long)) codes[li].scatter_(1, dest, c) codes = codes[..., :S].contiguous() if sink is not None: codes[0] = torch.where(sink, torch.full_like(codes[0], SINK), codes[0]) big = torch.full_like(pos, _BIG)[None, :, :, None] p4 = pos[None, :, :, None].expand(B, n_s, L, per_span) minpos = torch.where(onehot, p4, big).amin(2).reshape(B, n_s * per_span) maxpos = torch.where(onehot, p4, -torch.ones_like(p4)).amax(2).reshape(B, n_s * per_span) kb = torch.stack([torch.where(minpos < _BIG, minpos // block, torch.full_like(minpos, 1)), torch.where(maxpos >= 0, maxpos // block, torch.zeros_like(maxpos))], dim=-1) return GroupIndex(span_start=st, span_len=L, per_span=per_span, prefix=prefix, codes=codes, doc_start=doc_start, g_close=g_close, g_doc=g_doc, g_minpos=minpos, g_kb=kb, any_doc=any_doc) def counts(index: GroupIndex, gid: torch.Tensor, lo: torch.Tensor, hi: torch.Tensor) -> torch.Tensor: """Members of each group `gid` [B, …] at positions in [lo, hi] (inclusive; broadcast to gid's shape), int32.""" B = gid.shape[0] L, K = index.span_len, index.per_span s = torch.div(gid, K, rounding_mode="floor") l = gid - s * K st = index.span_start[s] o_hi = (hi + 1 - st).clamp(0, L) o_lo = torch.minimum((lo - st).clamp(0, L), o_hi) flat = index.prefix[:B].reshape(B, -1) # the first B rows (probes pass one row) def at(o): i = ((s * (L + 1) + o) * K + l).reshape(B, -1) return flat.gather(1, i).view(gid.shape) return (at(o_hi) - at(o_lo)).clamp(min=0) @torch.no_grad() def choose(score: torch.Tensor, cand: torch.Tensor, index: GroupIndex, q_pos: torch.Tensor, *, m: int, cap: int, raw_window: int) -> tuple[torch.Tensor, torch.Tensor]: """One query chunk: top-m candidates, then the places each takes. score / cand [B, ch, G], q_pos [ch] long. Returns ids [B, ch, m'] long (m' = min(m, G), best first) and off [B, ch, m'] int32: places used before each chosen group, `cap` where the group is not a real choice or the cap is already full.""" B, ch, G = score.shape mm = min(int(m), G) top = score.masked_fill(~cand, float("-inf")).topk(mm, dim=-1) ids = top.indices valid = top.values > float("-inf") lo = index.doc_start[:, q_pos][..., None].expand(B, ch, mm) hi = (q_pos - int(raw_window))[None, :, None].expand(B, ch, mm) cnt = torch.where(valid, counts(index, ids, lo, hi), torch.zeros_like(ids, dtype=torch.int32)) off = cnt.cumsum(-1) - cnt off = torch.where(valid & (off < cap), off, torch.full_like(off, cap)) return ids, off.to(torch.int32) class OpenTable: """The per-query table T [B, S, G] int16 and the key blocks each 128-query block may open, built chunk by chunk.""" def __init__(self, index: GroupIndex, B: int, S: int, *, cap: int, block: int = 128): dev = index.codes.device self.index, self.S, self.cap, self.block = index, S, int(cap), block G = index.n_groups self.T = torch.full((B, S, max(G, 1)), int(cap), dtype=torch.int16, device=dev) self.nqb, self.nkb = -(-S // block), -(-S // block) self.need = torch.zeros(B, self.nqb * self.nkb + 1, dtype=torch.bool, device=dev) self.span_blocks = -(-index.span_len // block) + 1 def add(self, s0: int, ids: torch.Tensor, off: torch.Tensor) -> None: B, ch, m = ids.shape if m == 0: return self.T[:, s0:s0 + ch].scatter_(2, ids, off.to(torch.int16)) q_pos = torch.arange(s0, s0 + ch, device=ids.device) qb = (q_pos // self.block)[None, :, None] kb = self.index.g_kb.gather(1, ids.reshape(B, -1, 1).expand(B, ch * m, 2)).view(B, ch, m, 2) live = off < self.cap dummy = self.nqb * self.nkb for d in range(self.span_blocks): b_ = kb[..., 0] + d ok = live & (b_ <= kb[..., 1]) & (b_ < self.nkb) idx = torch.where(ok, qb * self.nkb + b_, torch.full_like(b_, dummy)) self.need.scatter_(1, idx.reshape(B, -1), True) def extra_blocks(self) -> torch.Tensor: """[B, nqb, nkb] long: raw key blocks with an opened token for some query of the block (βˆ’1 = none).""" B = self.need.shape[0] need = self.need[:, :-1].view(B, self.nqb, self.nkb) ids = torch.arange(self.nkb, device=need.device)[None, None].expand_as(need) return torch.where(need, ids, torch.full_like(ids, -1)) class ChoiceList: """E33t stage C (plan Β§10.1–2): each query's choice kept as a list instead of the table T [B, S, G], whose size grows with SΒ² (4.3 GB at 128k, 275 GB at 1M): the chosen groups `ids` [B, S, m] int32, best first, and the places used before each, `off` [B, S, m] int16 (`cap` = not a real choice, or the cap already full) β€” 0.8 GB at 1M with m = 128. Same `add` as OpenTable, so `note_open_table` / `lsa_open_table` fill either. Evaluation only. `opened` gives each query's opened raw positions, the same tokens T opens when every token is in at most one group per forward (one code layer: the catalogue's notes on non-overlapping pages, LSA's closed blocks; more layers are refused): chosen group g with off_g < cap opens its members in [doc_start(i), i βˆ’ raw_window], oldest first, at most cap βˆ’ off_g of them, i.e. members[g, r0_g + r] for r < min(cnt_g, cap βˆ’ off_g), with r0_g its members before doc_start(i) and cnt_g its members in the range (the count `choose` used). `row0` (cached decoding, nn/incremental.py): the list holds the queries [row0, row0 + S) only (positions stay absolute in `add` / `opened`); `members` reuses a members table built once for this index.""" def __init__(self, index: GroupIndex, B: int, S: int, *, cap: int, m: int, row0: int = 0, members: Optional[torch.Tensor] = None): if int(index.codes.shape[0]) != 1: raise NotImplementedError("the choice list needs one code layer (spans that do not overlap)") dev = index.codes.device self.index, self.S, self.cap = index, S, int(cap) self.row0 = int(row0) self.m = max(1, int(m)) self.ids = torch.zeros(B, S, self.m, dtype=torch.int32, device=dev) self.off = torch.full((B, S, self.m), self.cap, dtype=torch.int16, device=dev) self._members: Optional[torch.Tensor] = members def add(self, s0: int, ids: torch.Tensor, off: torch.Tensor) -> None: ch, mm = ids.shape[1], ids.shape[2] if mm == 0: return r = s0 - self.row0 self.ids[:, r:r + ch, :mm] = ids.to(torch.int32) self.off[:, r:r + ch, :mm] = off.to(torch.int16) def members(self) -> torch.Tensor: """[B, G, F] long: each group's member positions, oldest first (βˆ’1 = none); F = the largest group (β‰₯ 1).""" if self._members is None: gi = self.index B, S = gi.codes.shape[1], gi.codes.shape[2] K, L, G = gi.per_span, gi.span_len, gi.n_groups c = gi.codes[0].long() # [B, S] is_m = c >= 0 gid = torch.where(is_m, torch.div(c, ORD_MOD, rounding_mode="floor"), torch.zeros_like(c)) s = torch.div(gid, K, rounding_mode="floor") l = gid - s * K j = torch.arange(S, device=c.device)[None].expand(B, S) o = (j - gi.span_start[s]).clamp(0, L) rank = gi.prefix.reshape(B, -1).gather(1, (s * (L + 1) + o) * K + l) # members of g before j Fm = max(1, int(gi.prefix[:, :, L].max())) if gi.prefix.numel() else 1 mem = torch.full((B, G * Fm + 1), -1, dtype=torch.long, device=c.device) dest = torch.where(is_m & (rank < Fm), gid * Fm + rank, torch.full_like(gid, G * Fm)) mem.scatter_(1, dest, j) self._members = mem[:, :G * Fm].view(B, G, Fm) return self._members def opened(self, s0: int, s1: int, raw_window: int) -> tuple[torch.Tensor, torch.Tensor]: """Opened raw positions of queries [s0, s1): pos [B, ch, mΒ·F] long (0 where not opened) and ok [B, ch, mΒ·F] bool. At most `cap` entries of a query are ok, each a distinct earlier token of its document.""" gi = self.index mem = self.members() B, G, Fm = mem.shape ids = self.ids[:, s0 - self.row0:s1 - self.row0].long() off = self.off[:, s0 - self.row0:s1 - self.row0].to(torch.int32) ch, m = ids.shape[1], ids.shape[2] qp = torch.arange(s0, s1, device=ids.device) live = off < self.cap ds = gi.doc_start[:, s0:s1][..., None].expand(B, ch, m) hi = (qp - int(raw_window))[None, :, None].expand(B, ch, m) cnt = torch.where(live, counts(gi, ids, ds, hi), torch.zeros_like(off)) n = torch.minimum(cnt, self.cap - off).clamp(min=0) r0 = counts(gi, ids, torch.zeros_like(ds), ds - 1) # members before the document r = torch.arange(Fm, device=ids.device) take = r0[..., None] + r # [B, ch, m, F] ok = (r < n[..., None]) & (take < Fm) flat = ids[..., None] * Fm + take.clamp(max=Fm - 1) pos = mem.reshape(B, -1).gather(1, flat.reshape(B, -1)).view(B, ch, m, Fm) ok = ok & (pos >= 0) pos = torch.where(ok, pos, torch.zeros_like(pos)) return pos.reshape(B, ch, m * Fm), ok.reshape(B, ch, m * Fm) # Flex attention addresses the buffers a mask_mod captures with 32-bit offsets: a buffer of 2Β³ΒΉ elements or more is # read out of bounds (illegal memory access; E33p notes at 128k: T is 131,072 Γ— ~21,800 β‰ˆ 2.9e9, 2026-11-07). _FLEX_MAX_NUMEL = 2**31 - 1 def _split_queries(T: torch.Tensor) -> tuple[list[torch.Tensor], int]: """T [B, S, G] as query chunks of fewer than 2Β³ΒΉ elements each (fresh tensors), and the chunk length. One chunk (T itself, no copy) up to that size, i.e. at every length the models train on; beyond it, one extra copy of T.""" B, S, G = (int(x) for x in T.shape) if B * S * G <= _FLEX_MAX_NUMEL: return [T], S qc = max(1, _FLEX_MAX_NUMEL // (B * G)) return [T[:, i:i + qc].clone() for i in range(0, S, qc)], qc def open_term(T: torch.Tensor, codes: torch.Tensor, *, cap: int, raw_window: int) -> Callable: """mask_mod piece (b, q, j) β†’ bool for raw key j (already clamped to [0, S)): j opened for query q. It does not test documents: every caller ANDs it with its own causal same-document test (LSA buckets may mix documents).""" n_layers = int(codes.shape[0]) G = int(T.shape[-1]) cap_i, rw = int(cap), int(raw_window) parts, qc = _split_queries(T) def t_at(b, q, g): if len(parts) == 1: return parts[0][b, q, g] out = None for ci, P in enumerate(parts): # static: one lookup per chunk, the query's own chunk wins v = P[b, torch.clamp(q - ci * qc, 0, int(P.shape[1]) - 1), g] out = v if out is None else torch.where(q >= ci * qc, v, out) return out def opened(b, q, j): hit = None for li in range(n_layers): c = codes[li, b, j] g = torch.div(c, ORD_MOD, rounding_mode="floor") o = c - g * ORD_MOD h = (c >= 0) & (t_at(b, q, torch.clamp(g, 0, G - 1)).to(torch.int32) + o < cap_i) hit = h if hit is None else hit | h return hit & (q - j >= rw) return opened def dense_open(T: torch.Tensor, codes: torch.Tensor, *, cap: int, raw_window: int, q_idx: Optional[torch.Tensor] = None, doc: Optional[torch.Tensor] = None) -> torch.Tensor: """[B, Q, S] bool β€” the same rule as `open_term` for the query rows `q_idx` (default: all); with `doc` [B, S], also the same-document test, i.e. exactly the opened tokens the read uses.""" B, S = codes.shape[1], codes.shape[2] G = T.shape[-1] if q_idx is None: q_idx = torch.arange(S, device=T.device) Tq = T[:, q_idx].to(torch.int32) # [B, Q, G] Q = Tq.shape[1] hit = torch.zeros(B, Q, S, dtype=torch.bool, device=T.device) for li in range(codes.shape[0]): c = codes[li].to(torch.int64) g = torch.div(c, ORD_MOD, rounding_mode="floor") o = c - g * ORD_MOD tg = Tq.gather(2, g.clamp(0, G - 1)[:, None, :].expand(B, Q, S)) hit |= (c >= 0)[:, None, :] & (tg + o[:, None, :] < cap) j = torch.arange(S, device=T.device) hit = hit & ((q_idx[:, None] - j[None, :]) >= raw_window)[None] if doc is not None: hit = hit & (doc[:, q_idx][:, :, None] == doc[:, None, :]) & (doc[:, q_idx] >= 0)[:, :, None] return hit # --------------------------------------------------------------------------------------- E33p notes and pages @dataclass class NoteOpen: """Per-forward state of the note-indexed read (built once after the writer, `PerceiverARLM._run_layers`).""" assign: torch.Tensor # [B, n_w, K, W] fp32 (grad) β€” A[t, n], last latent round, heads averaged page_tok: torch.Tensor # [n_w, W] long β€” row index of each page slot (clamped) groups: GroupIndex # what opens: the notes, or the pages mode: str # "none" | "notes" | "pages" k: int # groups chosen per query cap: int per_page: int # notes per page (K) # E33t, the catalogue read (defaults = E33p) read: str = "gist" # "index": the notes only choose what opens score: str = "sum_softmax" # "max_cos": cosine, best query head levels: int = 1 # 2: pages first, then their notes keep_pages: int = 16 new_per_pass: bool = False # a pass may not open notes the query opened earlier labels: Optional[torch.Tensor] = None # [B, n_w, W] filed note per page slot (balanced filing), βˆ’1 = none pick: Optional[torch.Tensor] = None # [B, n_w, W] valid page slots def balance_assign(A: torch.Tensor, valid: torch.Tensor, iters: int = 3, eps: float = 1e-6) -> torch.Tensor: """E33t balanced filing, soft part: Sinkhorn iterations on each page's assignment so every note receives about the same mass (SwAV's equipartition). A [B, n_w, K, W] (a distribution over the K notes per token), valid [B, n_w, W] bool β†’ Γ‚ [B, n_w, K, W]: per page, each note's mass β†’ n_valid / K, each valid token's mass over notes β†’ 1 (exact after the last step); invalid tokens 0. Differentiable.""" m = valid[:, :, None, :].to(A.dtype) a = A * m K = A.shape[2] target = m.sum(-1, keepdim=True) / K # [B, n_w, 1, 1] for _ in range(int(iters)): a = a * (target / a.sum(-1, keepdim=True).clamp_min(eps)) a = a / a.sum(2, keepdim=True).clamp_min(eps) * m return a @torch.no_grad() def file_capped(A_hat: torch.Tensor, valid: torch.Tensor, cap: int = 16) -> torch.Tensor: """E33t balanced filing, hard part: each valid page slot is filed under one note, at most `cap` per note. Tokens propose their notes best first (by Γ‚); a note accepts its proposers best first until full; a rejected token proposes its next note in the next round. With K Β· cap β‰₯ W every token is filed within K rounds (a token rejected by all K notes would need all K full). A_hat [B, n_w, K, W], valid [B, n_w, W] β†’ labels [B, n_w, W] long, βˆ’1 = not valid.""" B, n_w, K, W = A_hat.shape a = A_hat.detach().float().permute(0, 1, 3, 2).reshape(-1, W, K) # [P, W, K] v = valid.reshape(-1, W).bool() P = a.shape[0] dev = a.device labels = torch.full((P, W), -1, dtype=torch.long, device=dev) fill = torch.zeros(P, K + 1, dtype=torch.long, device=dev) order = a.argsort(dim=-1, descending=True) # [P, W, K] idx = torch.arange(W, device=dev)[None].expand(P, W) for r in range(K): todo = v & (labels < 0) if not bool(todo.any()): break prop = order[..., r] # [P, W] sc = a.gather(-1, prop[..., None]).squeeze(-1).clamp(0.0, 1.0) key = torch.where(todo, prop, torch.full_like(prop, K)) # K = not proposing srt = torch.argsort(key.float() * 2.0 - sc, dim=-1) # note asc, score desc sk = key.gather(-1, srt) new = torch.ones_like(sk, dtype=torch.bool) new[:, 1:] = sk[:, 1:] != sk[:, :-1] start = torch.cummax(torch.where(new, idx, torch.zeros_like(idx)), dim=-1).values rank = torch.empty_like(idx).scatter_(-1, srt, idx - start) # rank among its note's proposers room = (cap - fill).gather(-1, key) accept = todo & (rank < room) labels = torch.where(accept, prop, labels) fill.scatter_add_(-1, torch.where(accept, prop, torch.full_like(prop, K)), accept.long()) return labels.view(B, n_w, W) def page_keys(k: torch.Tensor, page_tok: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: """E33t two-level search: Ο€_p = mean of the page's valid tokens' keys. k [B, S, 1, dh], page_tok [n_w, W], valid [B, n_w, W] β†’ [B, n_w, dh] fp32 (no gradient needed: the choice is made without one).""" B = k.shape[0] n_w, W = page_tok.shape kp = k[:, page_tok.reshape(-1), 0].detach().float().view(B, n_w, W, -1) m = valid.to(kp.dtype)[..., None] return (kp * m).sum(2) / m.sum(2).clamp_min(1.0) def tied_note_keys(assign: torch.Tensor, k: torch.Tensor, page_tok: torch.Tensor) -> torch.Tensor: """ΞΊ_n = Ξ£_t A[t, n] k_t / Ξ£_t A[t, n] over the note's page. assign [B, n_w, K, W], k [B, S, g, dh] β†’ [B, n_wΒ·K, g, dh] (fp32, outside autocast; a note with no mass gets ΞΊ = 0).""" B, n_w, K, W = assign.shape g, dh = k.shape[2], k.shape[3] with torch.autocast(device_type=k.device.type, enabled=False): kp = k[:, page_tok.reshape(-1)].float().view(B, n_w, W, g, dh) a = assign.float() num = torch.einsum("bnkw,bnwgd->bnkgd", a, kp) den = a.sum(-1)[..., None, None].clamp_min(1e-6) return (num / den).reshape(B, n_w * K, g, dh) def note_groups(assign: torch.Tensor, pick: torch.Tensor, page_starts: list[int], *, S: int, doc_start: torch.Tensor, slot_close: torch.Tensor, slot_doc: torch.Tensor, mode: str, labels: Optional[torch.Tensor] = None) -> GroupIndex: """Notes (member = argmax_k A on picked tokens, or the given filing `labels` [B, n_w, W]) or pages (member = picked) as groups. slot_* [B, n_wΒ·K].""" B, n_w, K, W = assign.shape if mode == "pages": member = torch.where(pick, torch.zeros_like(pick, dtype=torch.long), torch.full_like(pick, -1, dtype=torch.long)) g_close, g_doc, per = slot_close[:, ::K], slot_doc[:, ::K], 1 else: best = labels if labels is not None else assign.detach().argmax(dim=2) # [B, n_w, W] member = torch.where(pick, best, torch.full_like(best, -1)) g_close, g_doc, per = slot_close, slot_doc, K return groups_from_spans(member, page_starts, S=S, per_span=per, doc_start=doc_start, g_close=g_close.contiguous(), g_doc=g_doc.contiguous()) @torch.no_grad() def note_open_table(q: torch.Tensor, kappa: torch.Tensor, no: NoteOpen, *, doc: torch.Tensor, slot_close: torch.Tensor, slot_doc: torch.Tensor, raw_window: int, chunk: int = 0, exclude: Optional[torch.Tensor] = None, page_key: Optional[torch.Tensor] = None, impl: str = "table", q_offset: int = 0, members: Optional[torch.Tensor] = None): """E33p choice for every query: s_i(n) = Ξ£_h softmax_n(q_{i,h}Β·ΞΊ_n / √dh) over the notes visible to i (closed rule), eligible = visible ∧ a member older than i's window; notes: top-k notes; pages: the page score is the sum of its notes' scores, top-k eligible pages. q [B, S, h, dh], ΞΊ [B, C, 1, dh]. E33t: `no.score = "max_cos"` scores s_i(n) = max_h cos(q_{i,h}, ΞΊ_n); `exclude` [B, S, G] bool removes the groups a query opened in earlier passes; `page_key` [B, n_w, dh] with `no.levels = 2` keeps, per query, the `no.keep_pages` best visible pages holding an eligible note (same score rule on the page keys) and lets only their notes compete. `impl = "list"` (E33t stage C, evaluation): the choice as a ChoiceList instead of the table. `q_offset` (cached decoding, nn/incremental.py; list only): q holds the queries [q_offset, q_offset + Sq) of a row of doc.shape[1] tokens; `members` passes the index's members table along (built once per index).""" B, Sq, h, dh = q.shape q0 = int(q_offset) if (q0 or Sq != doc.shape[1]) and (impl != "list" or exclude is not None): raise ValueError("a query range is for the list read without pass exclusion") S = q0 + Sq C = kappa.shape[1] K = no.per_page gi = no.groups dev = q.device G = gi.n_groups if chunk <= 0: chunk = max(128, min(1024, (1 << 25) // max(B * h * C, 1) // 128 * 128)) kb = kappa[:, :, 0].float() sc = dh ** -0.5 cos = no.score == "max_cos" if cos: kb = F.normalize(kb, dim=-1) two = no.levels == 2 and page_key is not None and no.mode == "notes" pk = F.normalize(page_key.float(), dim=-1) if two else None tab = (ChoiceList(gi, B, Sq, cap=no.cap, m=min(int(no.k), G), row0=q0, members=members) if impl == "list" else OpenTable(gi, B, S, cap=no.cap)) n_vis_ok = (slot_doc >= 0) & (slot_close >= 0) for s0 in range(q0, S, chunk): s1 = min(S, s0 + chunk) qp = torch.arange(s0, s1, device=dev) dq = doc[:, s0:s1] vis = (n_vis_ok[:, None, :] & (slot_doc[:, None, :] == dq[..., None]) & (dq[..., None] >= 0) & (slot_close[:, None, :] <= qp[None, :, None])) # [B, ch, C] qc = q[:, s0 - q0:s1 - q0].float() if cos: qc = F.normalize(qc, dim=-1) s_note = torch.einsum("bshd,bcd->bshc", qc, kb).amax(2) # [B, ch, C] else: lg = torch.einsum("bshd,bcd->bshc", qc, kb) * sc p = torch.softmax(lg.masked_fill(~vis[:, :, None], float("-inf")), dim=-1) s_note = torch.nan_to_num(p, nan=0.0).sum(2) # [B, ch, C] if no.mode == "pages": score = s_note.view(B, s1 - s0, C // K, K).sum(-1) gvis = vis.view(B, s1 - s0, C // K, K).any(-1) else: score, gvis = s_note, vis cand = gvis & (gi.g_minpos[:, None, :] <= (qp - raw_window)[None, :, None]) if exclude is not None: cand = cand & ~exclude[:, s0:s1] if two: n_w = C // K ps = torch.einsum("bshd,bpd->bshp", qc, pk).amax(2) # [B, ch, n_w] pok = cand.view(B, s1 - s0, n_w, K).any(-1) kp = min(int(no.keep_pages), n_w) top = ps.masked_fill(~pok, float("-inf")).topk(kp, dim=-1) keep = torch.zeros_like(pok).scatter_(-1, top.indices, top.values > float("-inf")) cand = cand & keep.repeat_interleave(K, dim=-1) ids, off = choose(score, cand, gi, qp, m=no.k, cap=no.cap, raw_window=raw_window) tab.add(s0, ids, off) return tab def _masked_rank_corr(a: torch.Tensor, b: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """Mean over rows with β‰₯ 3 masked entries of the Spearman correlation of a and b on the masked entries. [Q, G].""" big = torch.finfo(torch.float32).max def ranks(x): x = x.float().masked_fill(~mask, -big) return x.argsort(-1).argsort(-1).float() ra, rb = ranks(a), ranks(b) n = mask.sum(-1, keepdim=True).clamp_min(1).float() m = mask.float() ma, mb = (ra * m).sum(-1, keepdim=True) / n, (rb * m).sum(-1, keepdim=True) / n da, db = (ra - ma) * m, (rb - mb) * m c = (da * db).sum(-1) / ((da.pow(2).sum(-1) * db.pow(2).sum(-1)).sqrt().clamp_min(1e-9)) ok = mask.sum(-1) >= 3 return c[ok].mean() if bool(ok.any()) else torch.zeros((), device=a.device) def index_loss(q: torch.Tensor, k: torch.Tensor, sink_k: Optional[torch.Tensor], kappa: torch.Tensor, opened: "OpenTable", *, doc: torch.Tensor, raw_window: int, n_queries: int, n_neg: int, log_tau: torch.Tensor, seen: Optional[torch.Tensor] = None, generator: Optional[torch.Generator] = None) -> tuple[torch.Tensor, dict]: """E33t index loss for one pass of the catalogue read: the notes' scores learn to predict where the read's attention lands. For `n_queries` query positions per row (evenly spaced from the window on): the read's softmax over sinks β€– its window β€– its opened tokens is recomputed (fp32, detached: the target); target mass of a chosen note = the probability on its opened tokens; of a negative (one of `n_neg` sampled choosable, unchosen notes, not in `seen`) = the probability its eligible members would get with the same normaliser; both averaged over heads and renormalised over the set. Prediction = softmax over the set of Ο„ Β· max_h cos(q_{i,h}, ΞΊ_n), q detached, ΞΊ with gradient, Ο„ = exp(log_tau). Loss = KL(target β€– prediction), mean over queries with β‰₯ 2 notes in the set. q [B, S, h, dh], k [B, S, 1, dh], sink_k [n, dh] or None, ΞΊ [B, G, 1, dh], doc [B, S] (βˆ’1 = pad), seen [B, S, G] bool. Returns (loss, stats) with stats `kl`, `corr` (Spearman of score and target mass on the chosen notes) and `set` (notes per query).""" B, S, h, dh = q.shape gi = opened.index G = gi.n_groups cap = opened.cap dev = q.device rw = int(raw_window) lo = min(rw, S - 1) rows = torch.linspace(lo, S - 1, max(1, min(int(n_queries), S - lo)), device=dev).round().long().unique() Q = rows.numel() scale = dh ** -0.5 losses, corrs, sizes = [], [], [] tau = log_tau.exp() j = torch.arange(S, device=dev) with torch.autocast(device_type=dev.type, enabled=False): for b in range(B): d = doc[b] ok_q = d[rows] >= 0 qb = q[b, rows].detach().float() # [Q, h, dh] lg = torch.einsum("qhd,sd->hqs", qb, k[b, :, 0].detach().float()) * scale # [h, Q, S] causal = (j[None] <= rows[:, None]) & (d[None] == d[rows][:, None]) & ok_q[:, None] win = causal & ((rows[:, None] - j[None]) < rw) op = dense_open(opened.T[b:b + 1], gi.codes[:, b:b + 1], cap=cap, raw_window=rw, q_idx=rows, doc=doc[b:b + 1])[0] & causal & ~win allowed = win | op parts = [lg.masked_fill(~allowed[None], float("-inf"))] if sink_k is not None and sink_k.shape[0] > 0: parts.append(torch.einsum("qhd,nd->hqn", qb, sink_k.detach().float()) * scale) lse = torch.logsumexp(torch.cat(parts, -1), dim=-1) # [h, Q] pw = torch.exp(lg - lse[..., None]).mean(0) # [Q, S] would-be, head mean elig = causal & ~win m_open = torch.zeros(Q, G + 1, device=dev) m_elig = torch.zeros(Q, G + 1, device=dev) for li in range(gi.codes.shape[0]): c = gi.codes[li, b] gid = torch.where(c >= 0, torch.div(c, ORD_MOD, rounding_mode="floor"), torch.full_like(c, G)).long() gq = gid[None].expand(Q, S) m_open.scatter_add_(1, torch.where(op, gq, torch.full_like(gq, G)), pw * op) m_elig.scatter_add_(1, torch.where(elig, gq, torch.full_like(gq, G)), pw * elig) m_open, m_elig = m_open[:, :G], m_elig[:, :G] chosen = (opened.T[b, rows].to(torch.int32) < cap) & (m_open > 0) neg_ok = (m_elig > 0) & ~chosen if seen is not None: neg_ok = neg_ok & ~seen[b, rows] neg = torch.zeros_like(chosen) if n_neg > 0 and bool(neg_ok.any()): r = torch.rand(Q, G, device=dev, generator=generator).masked_fill(~neg_ok, -1.0) top = r.topk(min(int(n_neg), G), dim=-1) neg.scatter_(1, top.indices, top.values >= 0) in_set = chosen | neg t = torch.where(chosen, m_open, torch.where(neg, m_elig, torch.zeros_like(m_open))) t = t / t.sum(-1, keepdim=True).clamp_min(1e-12) qn = F.normalize(qb, dim=-1) kn = F.normalize(kappa[b, :, 0].float(), dim=-1) # grad β†’ ΞΊ s = torch.einsum("qhd,gd->qhg", qn, kn).amax(1) # [Q, G] logp = torch.log_softmax((tau * s).masked_fill(~in_set, float("-inf")), dim=-1) use = ok_q & (in_set.sum(-1) >= 2) if bool(use.any()): kl = (t * (torch.log(t.clamp_min(1e-12)) - logp)).masked_fill(~in_set, 0.0).sum(-1) losses.append(kl[use].mean()) corrs.append(_masked_rank_corr(s.detach(), m_open, chosen & use[:, None])) sizes.append(in_set[use].sum(-1).float().mean()) if not losses: z = (kappa.sum() + log_tau) * 0.0 return z, {"kl": z.detach(), "corr": z.detach(), "set": z.detach()} loss = torch.stack(losses).mean() return loss, {"kl": loss.detach(), "corr": torch.stack(corrs).mean(), "set": torch.stack(sizes).mean()} # ============================================================================================================== # nn/latent_memory.py # ============================================================================================================== # Sliding-window latent memory writer (E31). # # Each overlapping window of the *book* (the tokens before QUERY, or before the window # closes in text) is written by `K` addressed latent vectors that read the window **in # context**. The latents are projected into the global read's key/value space and appended # to it, like E21/E30 slots, but a slot here is a latent with its own state (residual + FFN), # not a weighted average of token K/V. # # Spec: docs/experiments_specs/ahead/E31_sliding_window_latent_memory.md # Plan: docs/experiments_specs/ahead/E31_sliding_window_latent_memory_plan.md # # `lm_slot_pos="reader"` (E31c, text): slot keys are returned un-rotated and the global read meets # them with the un-rotated query (NoPE for slots, RoPE kept for raw keys) β€” every note is "at the # reader", the text translation of E31's QUERY-anchored "boundary" keys. # # Shapes (claim scale): tok_emb [B,S,e] β†’ windows [BΒ·n_w, W, d_w] β†’ latents [BΒ·n_w, K(+1), D] # β†’ reader slots kΜ„, vΜ„ [B, n_wΒ·KΒ·m, g, dh] (normed + RoPE'd at the latent's expected # position), slot_doc / slot_side / slot_pos [B, n_wΒ·KΒ·m]. # # Two ways of giving tokens context before (or while) the latents read them: # * `page_bidir` β€” `lm_enc_layers` bidirectional attention layers inside each window, # then `lm_rounds` latent cross-attention rounds; # * `bixt` β€” no encoder; `lm_rounds` rounds of latents ⇄ tokens (BiXT), the tokens # reading the latents back after every latent update. # # `lm_competition` makes latents compete for tokens (softmax over latents per token and # head, then renormalise over tokens, Slot-Attention style). `lm_null_latent` adds one # latent that the reader never sees. Heads are never averaged: each head writes its own # slice of the latent. LM_CONTEXTS = ("page_bidir", "bixt") _ADDR_FEATS = 64 def _rope(): # lazy: nn.perceiver_ar_lm imports this module pass # nn.perceiver_ar_lm: in this file return rope_cos_sin, apply_rope def window_starts(seq_len: int, window: int, stride: int) -> tuple[int, ...]: pass # nn.perceiver_ar_lm: in this file return _swp_window_starts(seq_len, window, stride) @dataclass(frozen=True) class LMGeometry: window: int stride: int latents: int reader_tokens: int starts: tuple[int, ...] @property def n_windows(self) -> int: return len(self.starts) @property def n_slots(self) -> int: """Reader entries (latents Γ— reader tokens Γ— windows).""" return self.n_windows * self.latents * self.reader_tokens @property def tokens_per_latent(self) -> float: s = self.starts[-1] + self.window if self.starts else 0 return s / max(self.n_windows * self.latents, 1) def lm_geometry(cfg, seq_len: int) -> LMGeometry: """Fixed geometry (no auto-shrink). A row shorter than the window is one window.""" S = max(int(seq_len), 1) W = min(int(cfg.lm_window), S) st = max(1, min(int(cfg.lm_stride), W)) return LMGeometry( window=W, stride=st, latents=int(cfg.lm_latents), reader_tokens=int(cfg.lm_reader_tokens), starts=window_starts(S, W, st), ) def window_pick( side: torch.Tensor, doc: torch.Tensor, key_valid: Optional[torch.Tensor], starts: tuple[int, ...], window: int, ): """Per-window pooling rule shared by E30 (`sw_perceiver`) and E31. A window writes only from its **own earliest side** and from **one document** (the document of its last token on that side). Computed per window, so a token that is poolable in one window never leaks into another (the E30 `pool_valid` leak). Returns tok_idx [n_w, W] (clamped), pick [B, n_w, W], slot_doc_w [B, n_w] (βˆ’1 = empty), slot_side_w [B, n_w], has [B, n_w]. """ B, S = side.shape device = side.device st = torch.tensor(starts, device=device, dtype=torch.long) tok = st[:, None] + torch.arange(window, device=device) in_range = tok < S tok_c = tok.clamp(max=max(S - 1, 0)) side_w = side[:, tok_c] doc_w = doc[:, tok_c] ok = in_range[None] & (doc_w >= 0) if key_valid is not None: ok = ok & key_valid.bool()[:, tok_c] big = torch.full((), 10**6, device=device, dtype=side.dtype) min_side = torch.where(ok, side_w, big).min(dim=-1).values has = ok.any(dim=-1) min_side = torch.where(has, min_side, torch.zeros_like(min_side)) on_side = ok & (side_w == min_side[..., None]) idx = torch.arange(window, device=device) last = (on_side.to(torch.long) * (idx + 1)).amax(dim=-1).clamp(min=1) - 1 pick_doc = doc_w.gather(-1, last[..., None]).squeeze(-1) pick = on_side & (doc_w == pick_doc[..., None]) slot_doc_w = torch.where(has, pick_doc, torch.full_like(pick_doc, -1)) slot_side_w = torch.where(has, min_side, torch.zeros_like(min_side)) return tok_c, pick, slot_doc_w, slot_side_w, has def _boundary_pos(side, doc, pos, slot_doc, *, fallback): """RoPE position of each slot's reading boundary: the first receiver token (side β‰₯ 1) of the slot's document. Every receiver reads from at or after it, so the receiver–slot distance is the receiver's offset from QUERY at every book length. `fallback` where the document has no receiver (those slots are never read).""" B, S = side.shape n_doc = int(max(int(doc.max().item()), 0)) + 1 idx = torch.arange(S, device=side.device).expand(B, S) recv = torch.where((side >= 1) & (doc >= 0), idx, torch.full_like(idx, S)) first = torch.full((B, n_doc), S, dtype=torch.long, device=side.device) if side.device.type == "mps": # MPS has no int64 scatter-amin; int32 is exact for S < 2^31 first = first.int().scatter_reduce_(1, doc.clamp(min=0), recv.int(), reduce="amin").long() else: first.scatter_reduce_(1, doc.clamp(min=0), recv, reduce="amin") b_idx = first.gather(1, slot_doc.clamp(min=0)) # [B, C] ok = (b_idx < S) & (slot_doc >= 0) b_pos = pos.gather(1, b_idx.clamp(max=S - 1)) return torch.where(ok, b_pos, fallback) def scaled_slot_pos(read_pos: torch.Tensor, boundary: torch.Tensor, ref: int) -> torch.Tensor: """Order-preserving, length-invariant slot position: the slot sits before the reading boundary at its true distance, compressed so no distance exceeds `ref` (the training scale). Slots keep their order, and the query–slot RoPE distance stays in [0, ref] at any length.""" b = boundary.to(torch.float32) d = (b - read_pos.to(torch.float32)).clamp(min=0.0) return b - d * (float(ref) / b.clamp(min=float(ref))) def _sinusoid(pos: torch.Tensor, dim: int = _ADDR_FEATS) -> torch.Tensor: """pos [...] β†’ [..., dim] fixed sinusoid features (window-start address).""" half = dim // 2 inv = 1.0 / (10000 ** (torch.arange(half, device=pos.device, dtype=torch.float32) / half)) ang = pos.to(torch.float32)[..., None] * inv return torch.cat([ang.sin(), ang.cos()], dim=-1) class _SwiGLU(nn.Module): def __init__(self, d: int, ff: int): super().__init__() self.gate = nn.Linear(d, ff, bias=False) self.up = nn.Linear(d, ff, bias=False) self.down = nn.Linear(ff, d, bias=False) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x)) class PageEncoderLayer(nn.Module): """Bidirectional self-attention inside one window (+ SwiGLU). Keys outside `mask` are invisible; masked query rows still produce (ignored) outputs.""" def __init__(self, d: int, head_dim: int = 64): super().__init__() self.h = max(1, d // head_dim) self.dh = d // self.h self.norm1 = nn.RMSNorm(d) self.qkv = nn.Linear(d, 3 * d, bias=False) self.qn = nn.RMSNorm(self.dh) self.kn = nn.RMSNorm(self.dh) self.o = nn.Linear(d, d, bias=False) self.norm2 = nn.RMSNorm(d) self.ff = _SwiGLU(d, 2 * d) def forward(self, x, mask, cos, sin): _, apply_rope = _rope() Bn, W, d = x.shape q, k, v = self.qkv(self.norm1(x)).view(Bn, W, 3, self.h, self.dh).unbind(dim=2) q, k = apply_rope(self.qn(q), cos, sin), apply_rope(self.kn(k), cos, sin) attn_mask = mask[:, None, None, :].expand(Bn, 1, W, W) # rows whose window has no valid key would be all -inf β†’ let them see themselves attn_mask = attn_mask | torch.eye(W, dtype=torch.bool, device=x.device)[None, None] o = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), attn_mask=attn_mask ).transpose(1, 2) x = x + self.o(o.reshape(Bn, W, d)) return x + self.ff(self.norm2(x)) class LatentMemoryWriter(nn.Module): """K addressed latents per window, written from two-way context (E31).""" def __init__(self, cfg): super().__init__() self.cfg_ref = cfg e = int(cfg.token_embedding_dim) dw = int(cfg.lm_writer_dim) D = int(cfg.lm_latent_dim) hl = int(cfg.lm_heads) self.context = str(cfg.lm_context) self.K = int(cfg.lm_latents) self.n_null = 1 if bool(cfg.lm_null_latent) else 0 Kp = self.K + self.n_null self.hl, self.dhl, self.D, self.dw = hl, D // hl, D, dw self.W = int(cfg.lm_window) self.m = int(cfg.lm_reader_tokens) self.g, self.dh = int(cfg.num_kv_heads), int(cfg.head_dim) self.rounds = int(cfg.lm_rounds) self.competition = bool(cfg.lm_competition) # length-invariant options (the long-context ladder): no absolute window-start address, # and slot keys rotated at the reading boundary instead of the position they read self.addr_mode = str(getattr(cfg, "lm_addr", "window_start")) self.slot_pos_mode = str(getattr(cfg, "lm_slot_pos", "read")) self.slot_pos_ref = int(getattr(cfg, "slot_pos_ref", 2048) or 2048) # "detach" (text multi-hop, 2026-10-17): the key is built from the latent's state and read with the # gradient stopped, so a loss on where reads land (read targets, the LM through attention) trains only # the key projections; what a latent reads is shaped by its value alone. With one shared read, E33o's # note-level read target pulled the latent at a place name toward the person asked about, and the place # dropped out of its value (probe 68 β†’ 14 %). self.key_grad = str(getattr(cfg, "lm_key_grad", "full") or "full") # "address" (2026-10-18): "detach" plus a separate address read β€” each latent reads the page a second time, # with its own query and position prior, for its key alone. E33ok's stop kept the notes' content, but its keys # could only reuse the content read, so a note on a place name could no longer carry the person's name in its # key (compose 61 β†’ 42 %, lookup at 16k 89 β†’ 52 %). The address read sees the token states and the shared # projections with the gradient stopped, so nothing it learns moves the content read; its output joins the # key through `keyread_out`, zero at init (a warm start from a "detach" model is unchanged at step 0). if self.key_grad not in ("full", "detach", "address"): raise ValueError(f"lm_key_grad must be full | detach | address, got {self.key_grad!r}") std = float(cfg.init_std) # "table": the shared token table only (E31-E33); "embed": the decoder's whole input layer (table + up-projection # + norm, [.., hidden]) β€” the writer and the reader start from the same encoding (roadmap 17 Oct, idea 1) in_dim = int(cfg.hidden_size) if str(getattr(cfg, "lm_writer_input", "table") or "table") == "embed" else e self.in_proj = nn.Linear(in_dim, dw, bias=False) # unit-scale token states: without it tok (0.02) Γ— in_proj (0.02) β‰ˆ 0.002, and the first # residual update (β‰ˆ window average, ~0.3) wipes each token's identity before any pick self.in_norm = nn.RMSNorm(dw) n_enc = int(cfg.lm_enc_layers) if self.context == "page_bidir" else 0 self.enc = nn.ModuleList([PageEncoderLayer(dw) for _ in range(n_enc)]) self.enc_dh = self.enc[0].dh if n_enc else 64 # latents: identity (q) + address (window start) β€” warm, never zero; z0 is RMS-normed so # each latent starts at unit scale (its identity is not swamped by the first read) self.q = nn.Parameter(torch.randn(Kp, D)) self.addr = nn.Linear(_ADDR_FEATS, D, bias=False) self.z0_norm = nn.RMSNorm(D) self.z_norm = nn.RMSNorm(D) self.x_norm = nn.RMSNorm(dw) self.wq = nn.Linear(D, D, bias=False) self.wk = nn.Linear(dw, D, bias=False) self.wv = nn.Linear(dw, D, bias=False) self.wo = nn.Linear(D, D, bias=False) self.qn = nn.RMSNorm(self.dhl) self.kn = nn.RMSNorm(self.dhl) # per-latent, per-head position prior over the window: soft sub-pages at init prior = torch.zeros(Kp, hl, self.W) if bool(getattr(cfg, "lm_pos_prior", True)) and self.K > 0: t = torch.arange(self.W, dtype=torch.float32) sigma = max(self.W / self.K, 1.0) for k in range(self.K): c = (k + 0.5) * self.W / self.K prior[k] = (-0.5 * ((t - c) / sigma) ** 2).clamp(min=-4.0) self.prior = nn.Parameter(prior) if self.key_grad == "address": self.keyread_q = nn.Linear(D, D, bias=False) self.keyread_prior = nn.Parameter(prior[: self.K].clone()) self.keyread_norm = nn.RMSNorm(D) self.z_ffn_norm = nn.RMSNorm(D) self.z_ffn = _SwiGLU(D, 2 * D) if self.context == "bixt": hx = max(1, dw // 64) self.hx, self.dhx = hx, dw // hx self.xq = nn.Linear(dw, dw, bias=False) self.zk = nn.Linear(D, dw, bias=False) self.zv = nn.Linear(D, dw, bias=False) self.xo = nn.Linear(dw, dw, bias=False) self.xz_norm = nn.RMSNorm(D) self.x_ffn_norm = nn.RMSNorm(dw) self.x_ffn = _SwiGLU(dw, 2 * dw) # Reader entries. Values carry *what the latent read* (the heads' read-out of the last # round); keys combine that content with the latent's state (identity + address). # `to_v_state` (latent state β†’ value) starts at zero: at init the value is content, not # the latent's identity, which otherwise makes every row's slots nearly identical. self.out_norm = nn.RMSNorm(D) self.read_norm = nn.RMSNorm(D) self.to_k = nn.Linear(D, self.m * self.g * self.dh, bias=False) self.to_k_read = nn.Linear(D, self.m * self.g * self.dh, bias=False) self.to_v = nn.Linear(D, self.m * self.g * self.dh, bias=False) self.to_v_state = nn.Linear(D, self.m * self.g * self.dh, bias=False) if self.key_grad == "address": self.keyread_out = nn.Linear(D, self.m * self.g * self.dh, bias=False) self.k_out_norm = nn.RMSNorm(self.dh) self.last_diag: dict = {} self._last_k_bar = None self._last_assign = None # ------------------------------------------------------------------ helpers def participation(self) -> torch.Tensor: return sum(p.sum() for p in self.parameters()) * 0.0 def geometry(self, S: int) -> LMGeometry: return lm_geometry(self.cfg_ref, S) def _latent_read(self, z, x, mask, W): """Latents read tokens. z [Bn,Kp,D], x [Bn,W,dw], mask [Bn,W] β†’ (w [Bn,hl,Kp,W], out [Bn,Kp,D]).""" Bn, Kp, _ = z.shape q = self.qn(self.wq(self.z_norm(z)).view(Bn, Kp, self.hl, self.dhl)) xn = self.x_norm(x) k = self.kn(self.wk(xn).view(Bn, W, self.hl, self.dhl)) v = self.wv(xn).view(Bn, W, self.hl, self.dhl) logits = torch.einsum("bkhd,bwhd->bhkw", q, k) / math.sqrt(self.dhl) logits = logits + self.prior[:, :, :W].permute(1, 0, 2)[None].to(logits.dtype) m = mask[:, None, None, :] if self.competition: a = torch.softmax(logits.float(), dim=2) # compete over latents, per (head, token) a = a * m self._last_assign = a # E33p: the assignment over latents, before the renormalisation over tokens w = a / (a.sum(dim=-1, keepdim=True) + 1e-6) else: w = torch.softmax(logits.float().masked_fill(~m, float("-inf")), dim=-1) w = torch.nan_to_num(w, nan=0.0) w = w.to(v.dtype) read = torch.einsum("bhkw,bwhd->bkhd", w, v).reshape(Bn, Kp, self.D) self._last_read = read # per-head read-out (content), used for the reader's values/keys return w, self.wo(read) def _address_read(self, z, x, mask, W): """The key's own read (lm_key_grad="address"). z [Bn,K,D], x [Bn,W,dw] β†’ [Bn,K,D]. Token states, latent states and every shared module enter with the gradient stopped; only the keyread_* parameters learn here.""" Bn, K, _ = z.shape def rms(mod, t): w = mod.weight.detach() if mod.weight is not None else None return F.rms_norm(t, mod.normalized_shape, w, mod.eps) q = rms(self.qn, self.keyread_q(rms(self.z_norm, z.detach())).view(Bn, K, self.hl, self.dhl)) xn = rms(self.x_norm, x.detach()) k = rms(self.kn, F.linear(xn, self.wk.weight.detach()).view(Bn, W, self.hl, self.dhl)) v = F.linear(xn, self.wv.weight.detach()).view(Bn, W, self.hl, self.dhl) logits = torch.einsum("bkhd,bwhd->bhkw", q, k) / math.sqrt(self.dhl) logits = logits + self.keyread_prior[:K, :, :W].permute(1, 0, 2)[None].to(logits.dtype) w = torch.softmax(logits.float().masked_fill(~mask[:, None, None, :], float("-inf")), dim=-1) w = torch.nan_to_num(w, nan=0.0).to(v.dtype) return self.keyread_norm(torch.einsum("bhkw,bwhd->bkhd", w, v).reshape(Bn, K, self.D)) def _token_read(self, x, z): """BiXT back-step: tokens read the latents. x [Bn,W,dw], z [Bn,Kp,D] β†’ Ξ”x.""" Bn, W, _ = x.shape Kp = z.shape[1] q = self.xq(self.x_norm(x)).view(Bn, W, self.hx, self.dhx).transpose(1, 2) zn = self.xz_norm(z) k = self.zk(zn).view(Bn, Kp, self.hx, self.dhx).transpose(1, 2) v = self.zv(zn).view(Bn, Kp, self.hx, self.dhx).transpose(1, 2) o = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(Bn, W, self.dw) return self.xo(o) # ------------------------------------------------------------------ forward def forward(self, tok_emb, side, doc, key_valid, pos, rope_theta: float): rope_cos_sin, apply_rope = _rope() B, S, _ = tok_emb.shape geo = self.geometry(S) W, n_w, K, m = geo.window, geo.n_windows, self.K, self.m tok_c, pick, slot_doc_w, slot_side_w, has = window_pick(side, doc, key_valid, geo.starts, W) Bn = B * n_w x = self.in_norm(self.in_proj(tok_emb))[:, tok_c].reshape(Bn, W, self.dw) mask = pick.reshape(Bn, W) if len(self.enc): rel = torch.arange(W, device=x.device)[None] cos, sin = rope_cos_sin(rel, self.enc_dh, 10000.0, x.dtype) for layer in self.enc: x = layer(x, mask, cos, sin) starts = torch.tensor(geo.starts, device=x.device, dtype=torch.long) start_pos = pos[:, starts] # [B, n_w] position of each window start (per document) z = self.q[None].to(x.dtype).expand(Bn, -1, -1) if self.addr_mode == "window_start": z = z + self.addr(_sinusoid(start_pos).to(x.dtype)).reshape(Bn, 1, self.D) else: # keep `addr` in the graph (zero contribution) so every parameter gets a gradient z = z + 0.0 * self.addr.weight.sum() z = self.z0_norm(z) w = None for _ in range(max(self.rounds, 1)): w, dz = self._latent_read(z, x, mask, W) z = z + dz z = z + self.z_ffn(self.z_ffn_norm(z)) if self.context == "bixt": x = x + self._token_read(x, z) x = x + self.x_ffn(self.x_ffn_norm(x)) z = z[:, :K] read = self.read_norm(self._last_read[:, :K]) w_real = w[:, :, :K].float() # [Bn, hl, K, W] # address: expected position of what each latent read (mean over heads), detached w_avg = w_real.mean(dim=1) rel_idx = torch.arange(W, device=x.device, dtype=torch.float32) mass = w_avg.sum(-1).clamp(min=1e-6) p_rel = ((w_avg * rel_idx).sum(-1) / mass).detach().round().long().clamp(0, W - 1) p_abs = start_pos.reshape(Bn, 1) + p_rel # [Bn, K] zo = self.out_norm(z) zk, rk = (zo, read) if self.key_grad == "full" else (zo.detach(), read.detach()) kpre = self.to_k(zk) + self.to_k_read(rk) if self.key_grad == "address": kpre = kpre + self.keyread_out(self._address_read(z, x, mask, W)) kk = self.k_out_norm(kpre.view(Bn, K, m, self.g, self.dh)) vv = (self.to_v(read) + self.to_v_state(zo)).view(Bn, K, m, self.g, self.dh) C = n_w * K * m kk = kk.reshape(B, C, self.g, self.dh) vv = vv.reshape(B, C, self.g, self.dh) slot_pos = p_abs.reshape(B, n_w, K, 1).expand(B, n_w, K, m).reshape(B, C) slot_doc = slot_doc_w.repeat_interleave(K * m, dim=1) if self.slot_pos_mode == "boundary": slot_pos = _boundary_pos(side, doc, pos, slot_doc, fallback=slot_pos) elif self.slot_pos_mode == "scaled": bnd = _boundary_pos(side, doc, pos, slot_doc, fallback=slot_pos) slot_pos = scaled_slot_pos(slot_pos, bnd, self.slot_pos_ref) if self.slot_pos_mode == "mixed": # content pairs at QUERY, order pairs at the scaled distance pass # nn.perceiver_ar_lm: in this file bnd = _boundary_pos(side, doc, pos, slot_doc, fallback=slot_pos) lo = scaled_slot_pos(slot_pos, bnd, self.slot_pos_ref) cos_s, sin_s = rope_cos_sin_mixed(bnd, lo, self.dh, rope_theta, kk.dtype) slot_pos = bnd elif self.slot_pos_mode != "reader": cos_s, sin_s = rope_cos_sin(slot_pos, self.dh, rope_theta, kk.dtype) if self.slot_pos_mode != "reader": # "reader" (E31c): un-rotated, met by the un-rotated query kk = apply_rope(kk, cos_s, sin_s) slot_side = slot_side_w.repeat_interleave(K * m, dim=1) self._last_k_bar = kk # diagnostics only outside training: they force four host syncs per forward (E33n speed, 2026-11-04); # nothing reads them during training self.last_diag = {} if self.training else self._diagnostics(w, mask, geo) return { "k": kk, "v": vv, "slot_doc": slot_doc, "slot_side": slot_side, "slot_pos": slot_pos, "window_pick": pick, # E35: the latents themselves (state after reading, and what they read), [B, n_wΒ·K, D] each β€” the # memory entries a transmitter reads; unused by the E31 / E33 notebook read "z": zo.reshape(B, n_w * K, self.D), "read": read.reshape(B, n_w * K, self.D), "latent_pos": p_abs.reshape(B, n_w * K), "latent_doc": slot_doc_w.repeat_interleave(K, dim=1), # E33p: the last round's competition softmax over the real latents [Bn, hl, K, W] (None without competition) "assign": self._last_assign[:, :, :K] if self.competition else None, } @torch.no_grad() def _diagnostics(self, w, mask, geo) -> dict: """Per-head entropy / log(valid tokens), head diversity, latent usage (last round).""" wf = w.detach().float()[:, :, : self.K] # [Bn,hl,K,W] live = mask.any(-1) if not bool(live.any()): return {} wf, maskf = wf[live], mask[live] n_valid = maskf.sum(-1).clamp(min=2).float() # [Bl] p = wf / wf.sum(-1, keepdim=True).clamp(min=1e-12) ent = -(p * (p + 1e-12).log()).sum(-1) # [Bl,hl,K] ent_ratio = (ent / n_valid.log()[:, None, None]).mean() # head diversity: 1 βˆ’ mean pairwise cosine between heads' distributions per latent pn = F.normalize(p, dim=-1) sim = torch.einsum("bhkw,bgkw->bkhg", pn, pn) hl = sim.shape[-1] off = (sim.sum((-1, -2)) - sim.diagonal(dim1=-2, dim2=-1).sum(-1)) / max(hl * (hl - 1), 1) diversity = float(1.0 - off.mean()) usage = wf.sum(-1).mean((0, 1)) # mass each latent takes (competition: share of tokens) return { "entropy_over_log_valid": float(ent_ratio), "entropy_over_logW": float(ent_ratio), # probe print alias "head_diversity": diversity, "latent_usage_min": float(usage.min()), "latent_usage_max": float(usage.max()), "n_windows": geo.n_windows, "n_slots": geo.n_slots, "window": geo.window, "stride": geo.stride, "latents": geo.latents, "reader_tokens": geo.reader_tokens, "tokens_per_latent": geo.tokens_per_latent, } # ============================================================================================================== # nn/concept_memory.py # ============================================================================================================== # E37 β€” concept memory for the reading layer: encoder β†’ reasoner β†’ decoder read. # # Spec: docs/experiments_specs/ahead/E37_concept_memory.md. # # The three blocks, inside one causal language model (`PerceiverARLM`, `par_global_read = "concept"`): # # 1. **Encoder (memory).** The layers below the reading layer turn tokens into states x, keys k and values v. Every # closed block of `block` keys is grouped into `per_block` **concepts** by content: a balanced soft k-means on the # unit keys (Sinkhorn-balanced assignment, a few rounds, no gradient), each key filed under its best concept. A # concept keeps the **links to its member tokens** (their positions, for exact reads) and **sufficient statistics** # of them: count n, mean key ΞΌ_k, mean value ΞΌ_v, isotropic key variance σ², mean state z. Statistics add up, so # concepts of concepts are exact sums (the route to long pages and 10M tokens). # 2. **Reasoner.** A small looped transformer over the concept states z (`ConceptReasoner`): a concept attends to the # concepts of its own and earlier blocks of the same document, so it can connect ideas across the document. Its # output is added to each concept's value (zero at the start: the read begins as the plain summary read). # 3. **Decoder read.** Each query reads one softmax over: its document's first `sinks` tokens; the raw tokens of its # own block and the block before (a block-aligned window); the member tokens of the concepts with the largest # estimated attention mass (exact; best query head, best concept first until `top_k` tokens); and **one summary # entry for every other concept** of older blocks. A summary's logit is the second-order estimate of the # log-sum-exp of its members' logits (the exponential kernel's moment-generating function): # log n + qΒ·ΞΌ_k/√d + |q|Β² σ² / (2d), # and its value is ΞΌ_v (+ the reasoner's update). The same estimate picks what to open, so the largest # contributions are read exactly and the rest coarsely (a fast-multipole split: near field exact, far field by # moments). Every past token of the document is represented exactly once: inside the window, opened, or inside one # summary. With pure concepts (identical member keys) the summary read equals full attention. # # **Length scale** (`sum_len`, off by default): past the row length `sum_len` (set it to the training length), the # summaries' total weight in a query's softmax is multiplied by ρ = N_train / N, N being the keys the query's # summaries stand for and N_train the same count at the end of a `sum_len` row; up to that length ρ = 1 and nothing # changes. Without it the estimated far-field mass grows with the document and swamps the read past the training # length (E37 fade probe, 2026-11-08, e37b: 89 % β†’ 128 % of the windowβ†’dense gap at 64k, 128k loss 2.326 β†’ 2.155). # # Related work (2026-11-07 scout): SPLA (arXiv 2601.22379) estimates positional blocks' mass from mean and diagonal # covariance and reads unread blocks as residual linear attention; RetroInfer (2505.02922) estimates unread clusters as # centroid score Γ— size, training-free; LSA (2610.42147) clusters keys by Ward merges and picks by cosine, no summaries # in the paper. Here: balanced content clusters, natively trained, a softmax summary per cluster with gradient to the # members, choice by estimated mass, and a reasoner over the clusters. # # Shapes at the 100M scale, 16k row: S = 16,384; blocks of 512 β†’ 32 blocks, 64 concepts each, C = 2,048 summaries; # k, v [B, S, 1, 64]; z [B, C, 896]. # ------------------------------------------------------------------------------------------------ encoder @torch.no_grad() def farthest_points(keys: torch.Tensor, valid: torch.Tensor, n: int) -> torch.Tensor: """n unit keys per block by farthest-point sampling on cosine similarity. keys [N, L, d] unit, valid [N, L] β†’ [N, n, d]. Blocks with fewer valid keys than n repeat their last pick.""" N, L, d = keys.shape big = 2.0 first = valid.float().argmax(1) # first valid key idx = [first] maxsim = torch.einsum("nld,nd->nl", keys, keys[torch.arange(N), first]).masked_fill(~valid, big) for _ in range(n - 1): nxt = maxsim.argmin(1) idx.append(nxt) maxsim = torch.maximum(maxsim, torch.einsum("nld,nd->nl", keys, keys[torch.arange(N), nxt])) pick = torch.stack(idx, 1) # [N, n] return keys.gather(1, pick[..., None].expand(N, n, d)) @torch.no_grad() def sinkhorn_labels(keys: torch.Tensor, valid: torch.Tensor, n_concepts: int, *, iters: int = 3, tau: float = 0.05, rounds: int = 4) -> torch.Tensor: """Balanced soft k-means on unit keys, per block. keys [N, L, d] fp32 unit rows, valid [N, L] bool β†’ labels [N, L] long (the concept of each key, βˆ’1 where not valid). Centres start at n_concepts keys picked by farthest-point sampling (the first valid key, then each time the key least similar to those picked; deterministic and content-based, so interleaved topics separate). Each round: logits = keys Β· centres / tau, a log-domain Sinkhorn plan that gives every key mass 1 and every concept an equal share of the block's valid keys, then centres = normalised plan-weighted key sums. Labels = each key's best concept under the last plan (roughly balanced: the plan is, its argmax nearly so).""" N, L, d = keys.shape C = int(n_concepts) vf = valid.float() cent = farthest_points(keys, valid, C) seed = cent neg = torch.finfo(torch.float32).min / 4 n_valid = vf.sum(1, keepdim=True).clamp_min(1.0) # [N, 1] log_col = torch.log(n_valid / C) # each concept's share logp = None for _ in range(max(1, iters)): logits = torch.einsum("nld,ncd->nlc", keys, cent) / tau logp = logits.masked_fill(~valid[..., None], neg) for _ in range(rounds): logp = logp - torch.logsumexp(logp, dim=2, keepdim=True) # each key: mass 1 logp = logp.masked_fill(~valid[..., None], neg) logp = logp - torch.logsumexp(logp, dim=1, keepdim=True) + log_col[..., None] # each concept: L/C logp = logp - torch.logsumexp(logp, dim=2, keepdim=True) p = logp.exp() * vf[..., None] cent = F.normalize(torch.einsum("nlc,nld->ncd", p, keys) + 1e-12 * seed, dim=-1) labels = logp.argmax(-1) return torch.where(valid, labels, torch.full_like(labels, -1)) _SINKHORN_COMPILED = None def concept_labels(keys: torch.Tensor, valid: torch.Tensor, n_concepts: int, *, iters: int = 3, tau: float = 0.05) -> torch.Tensor: """`sinkhorn_labels`, through torch.compile when CONCEPT_COMPILE=1 and the keys are on CUDA (2026-11-14). The grouping is ~400 small kernels per call (63 farthest-point picks, then the Sinkhorn rounds), four calls per forward: a fixed ~50 ms per training step at 100M whatever the batch. Compiled it gives the same labels (checked on an RTX 3090 for 12, 60 and 126 blocks: 0 labels differ; tests/test_concept_memory_cuda.py) in 4.5 ms instead of 12 ms a call; the first call of each shape compiles for ~12 s. Off by default.""" global _SINKHORN_COMPILED if keys.is_cuda and os.environ.get("CONCEPT_COMPILE", "0") == "1": if _SINKHORN_COMPILED is None: import torch._dynamo.config as dyn_cfg dyn_cfg.cache_size_limit = max(int(getattr(dyn_cfg, "cache_size_limit", 8)), 128) _SINKHORN_COMPILED = torch.compile(sinkhorn_labels, dynamic=False) return _SINKHORN_COMPILED(keys, valid, n_concepts, iters=iters, tau=tau) return sinkhorn_labels(keys, valid, n_concepts, iters=iters, tau=tau) @dataclass class ConceptIndex: """One reading-layer call's concepts. C = n_blocks Β· per_block, concept c = block Β· per_block + slot.""" groups: GroupIndex # member links (exact reads), nn.exact_read centroid: torch.Tensor # [B, C, d] unit mean key (the choice rule; no gradient) n: torch.Tensor # [B, C] members (0 = empty) mu_k: torch.Tensor # [B, C, d] mean key (with gradient to the members' keys) var: torch.Tensor # [B, C] mean per-dimension key variance of the members mu_v: torch.Tensor # [B, C, d] mean value z: Optional[torch.Tensor] # [B, C, H] mean state of the members (the reasoner's input), or None block_of: torch.Tensor # [C] long, the block of each concept c_doc: torch.Tensor # [B, C] long, the document of the concept's block (βˆ’1: mixed, padding or empty) labels: torch.Tensor # [B, n_blocks, block] long, each key's concept within its block (βˆ’1: sink / pad) block: int per_block: int @property def n_concepts(self) -> int: return int(self.n.shape[1]) def build_concepts(k: torch.Tensor, v: torch.Tensor, x: Optional[torch.Tensor], doc: torch.Tensor, sink: torch.Tensor, *, block: int, per_block: int, iters: int = 3, tau: float = 0.05) -> Optional[ConceptIndex]: """Concepts of every block some query sees as old (block index ≀ last query's block βˆ’ 2). k, v [B, S, 1, d] (the reading layer's keys after their norm, no position code), x [B, S, H] or None, doc [B, S] (βˆ’1 = padding), sink [B, S] bool. The grouping carries no gradient; the statistics do (through the members' k, v and x).""" B, S = doc.shape d = k.shape[-1] nb = (S - 1) // block - 1 # blocks with at least one query two blocks later if nb <= 0: return None L = nb * block kk = k[:, :L, 0].float() # [B, L, d] vv = v[:, :L, 0].float() valid = ((doc >= 0) & ~sink)[:, :L] unit = F.normalize(kk.detach(), dim=-1).reshape(B * nb, block, d) labels = concept_labels(unit, valid.reshape(B * nb, block), per_block, iters=iters, tau=tau) labels = labels.view(B, nb, block) onehot = (labels[..., None] == torch.arange(per_block, device=k.device)).float() # [B, nb, block, K] n = onehot.sum(2) # [B, nb, K] inv = 1.0 / n.clamp_min(1.0) kb = kk.reshape(B, nb, block, d) mu_k = torch.einsum("bnlk,bnld->bnkd", onehot, kb) * inv[..., None] sq = torch.einsum("bnlk,bnl->bnk", onehot, (kb ** 2).sum(-1)) * inv var = (sq - (mu_k ** 2).sum(-1)).clamp_min(0.0) / d mu_v = torch.einsum("bnlk,bnld->bnkd", onehot, vv.reshape(B, nb, block, d)) * inv[..., None] z = None if x is not None: z = torch.einsum("bnlk,bnlh->bnkh", onehot, x[:, :L].float().reshape(B, nb, block, -1)) * inv[..., None] z = z.reshape(B, nb * per_block, -1).to(x.dtype) # the document of each block, when the whole block is one document (summaries never mix documents) db = doc[:, :L].reshape(B, nb, block) one_doc = (db == db[..., :1]).all(-1) & (db[..., 0] >= 0) blk_doc = torch.where(one_doc, db[..., 0], torch.full_like(db[..., 0], -1)) c_doc = blk_doc.repeat_interleave(per_block, dim=1) n_flat = n.reshape(B, nb * per_block) c_doc = torch.where(n_flat > 0, c_doc, torch.full_like(c_doc, -1)) block_of = torch.arange(nb, device=k.device).repeat_interleave(per_block) ds = doc_starts(doc) # member links for the exact reads; a concept may be opened by queries two blocks later (block-aligned window) member = labels g_close = ((block_of + 2) * block)[None].expand(B, -1).contiguous() gi = groups_from_spans(member, [b * block for b in range(nb)], S=S, per_span=per_block, doc_start=ds, g_close=g_close, g_doc=torch.zeros_like(g_close), any_doc=True, sink=sink) mu_k = mu_k.reshape(B, nb * per_block, d) return ConceptIndex(groups=gi, centroid=F.normalize(mu_k.detach(), dim=-1), n=n_flat, mu_k=mu_k, var=var.reshape(B, nb * per_block), mu_v=mu_v.reshape(B, nb * per_block, d), z=z, block_of=block_of, c_doc=c_doc, labels=labels, block=block, per_block=per_block) def token_update(cidx: ConceptIndex, dv: torch.Tensor, S: int) -> torch.Tensor: """The reasoner's concept updates spread to the member tokens: [B, C, d] β†’ [B, S, 1, d], zero for tokens outside the concept blocks and for sinks / padding.""" B, C, d = dv.shape nb, blk = cidx.labels.shape[1], cidx.block cid = cidx.labels + (torch.arange(nb, device=dv.device) * cidx.per_block)[None, :, None] cid = torch.where(cidx.labels >= 0, cid, torch.full_like(cid, C)).reshape(B, nb * blk) padded = torch.cat([dv, torch.zeros_like(dv[:, :1])], dim=1) # index C = no update out = padded.gather(1, cid[..., None].expand(B, nb * blk, d)) if S > nb * blk: out = torch.cat([out, torch.zeros(B, S - nb * blk, d, dtype=out.dtype, device=out.device)], dim=1) return out[:, :, None] def summary_logit(q: torch.Tensor, cidx: ConceptIndex, *, variance: bool = True) -> torch.Tensor: """Each concept's estimated log attention mass for each query and head, the logit of its summary entry: log n + qΒ·ΞΌ_k/√d + |q|Β² σ² / (2d). q [B, s, h, d] β†’ [B, s, h, C] fp32 (βˆ’inf for empty concepts).""" d = q.shape[-1] qf = q.float() lg = torch.einsum("bshd,bcd->bshc", qf, cidx.mu_k.float()) / math.sqrt(d) lg = lg + torch.where(cidx.n > 0, cidx.n.clamp_min(1.0).log(), torch.full_like(cidx.n, -math.inf))[:, None, None] if variance: lg = lg + ((qf ** 2).sum(-1, keepdim=True) / (2 * d)) * cidx.var[:, None, None] return lg @torch.no_grad() def summary_log_scale(ds: torch.Tensor, S: int, block: int, sum_len: int) -> Optional[torch.Tensor]: """log ρ of each query's summaries (the length scale), ρ = min(1, N_train / N): N the keys in the concept blocks the query sees (blocks wholly inside its document, two or more blocks before its own), N_train that count at the end of a `sum_len` row. ds [B, S] document starts β†’ [B, S] fp32, or None when `sum_len` ≀ 0 (off).""" if sum_len <= 0: return None n_train = max((sum_len - 1) // block - 1, 1) * block qi = torch.arange(S, device=ds.device)[None] first = (ds + block - 1) // block # first block of the document n = ((qi // block) - 1 - first).clamp_min(1) * block return torch.where(n > n_train, math.log(n_train) - n.float().log(), torch.zeros_like(n, dtype=torch.float32)) def set_concept_sum_len(model: nn.Module, sum_len: int) -> int: """Eval switch: the length scale of every concept read in `model` (0 = off). Returns the layers changed.""" n = 0 for m in model.modules(): c = getattr(m, "concept", None) if isinstance(c, dict) and "summaries" in c: c["sum_len"] = int(sum_len) n += 1 return n @torch.no_grad() def concept_open_table(q: torch.Tensor, cidx: ConceptIndex, *, top_k: int, width: int, variance: bool = True, chunk: int = 0) -> OpenTable: """Each query opens the concepts with the largest estimated attention mass (its summary logit, best query head), concepts of blocks two or more before its own, best first, until `top_k` member tokens (nn.exact_read.choose: members of the query's document only). The opened concepts leave the summary read. q [B, S, h, d].""" B, S, h, d = q.shape gi = cidx.groups C = cidx.n_concepts if chunk <= 0: chunk = max(128, min(1024, (1 << 25) // max(B * h * C, 1) // 128 * 128)) tab = OpenTable(gi, B, S, cap=top_k) for s0 in range(0, S, chunk): s1 = min(S, s0 + chunk) qp = torch.arange(s0, s1, device=q.device) score = summary_logit(q[:, s0:s1], cidx, variance=variance).amax(2) # [B, ch, C] visible = (gi.g_close[:, None, :] <= qp[None, :, None]) & torch.isfinite(score) ids, off = choose(torch.nan_to_num(score, neginf=-1e30), visible, gi, qp, m=width, cap=top_k, raw_window=cidx.block) tab.add(s0, ids, off) return tab # ------------------------------------------------------------------------------------------------ reasoner class ConceptReasoner(nn.Module): """A few tied pre-norm transformer layers over the concept states, run `loops` times with the input added back each loop (input injection). A concept attends to concepts of its own and earlier blocks in its document. z [B, C, H] β†’ value update [B, C, d] (zero at initialisation).""" def __init__(self, hidden: int, d_value: int, *, dim: int, layers: int, heads: int, loops: int): super().__init__() self.loops = max(1, int(loops)) self.inp = nn.Linear(hidden, dim, bias=False) self.blocks = nn.ModuleList() for _ in range(int(layers)): self.blocks.append(nn.ModuleDict(dict( n1=nn.RMSNorm(dim), qkv=nn.Linear(dim, 3 * dim, bias=False), o=nn.Linear(dim, dim, bias=False), n2=nn.RMSNorm(dim), up=nn.Linear(dim, 4 * dim, bias=False), down=nn.Linear(4 * dim, dim, bias=False)))) self.heads = int(heads) self.norm = nn.RMSNorm(dim) self.out = nn.Linear(dim, d_value, bias=False) nn.init.zeros_(self.out.weight) def forward(self, z: torch.Tensor, block_of: torch.Tensor, c_doc: torch.Tensor, loops: Optional[int] = None) -> torch.Tensor: B, C, _ = z.shape u = self.inp(z) ok = (c_doc >= 0) mask = ((block_of[None, :, None] >= block_of[None, None, :]) & (c_doc[:, :, None] == c_doc[:, None, :]) & ok[:, :, None] & ok[:, None, :]) mask = mask | torch.eye(C, dtype=torch.bool, device=z.device)[None] # no empty rows h = torch.zeros_like(u) for _ in range(int(loops or self.loops)): h = h + u # input injection for blk in self.blocks: a = blk["qkv"](blk["n1"](h)).view(B, C, 3, self.heads, -1).permute(2, 0, 3, 1, 4) o = F.scaled_dot_product_attention(a[0], a[1], a[2], attn_mask=mask[:, None]) h = h + blk["o"](o.transpose(1, 2).reshape(B, C, -1)) h = h + blk["down"](F.silu(blk["up"](blk["n2"](h)))) return self.out(self.norm(h)) # ------------------------------------------------------------------------------------------------ decoder read def _chosen_lookup(opened: Optional[OpenTable]): """(b, q, c) β†’ bool, c chosen by q (opened at least partly). None when nothing is opened.""" if opened is None: return None parts, qc = _split_queries(opened.T) cap = int(opened.cap) G = int(opened.T.shape[-1]) def chosen(b, q, c): c = torch.clamp(c, 0, G - 1) if len(parts) == 1: t = parts[0][b, q, c] else: t = None for ci, P in enumerate(parts): vv = P[b, torch.clamp(q - ci * qc, 0, int(P.shape[1]) - 1), c] t = vv if t is None else torch.where(q >= ci * qc, vv, t) return t.to(torch.int32) < cap return chosen def attend_concepts(q, k, v, *, cidx: Optional[ConceptIndex], dv: Optional[torch.Tensor], doc, key_valid, backend, opened: Optional[OpenTable], sink: torch.Tensor, ds: torch.Tensor, n_sinks: int, summaries: bool = True, variance: bool = True, dv_tok: Optional[torch.Tensor] = None, sum_len: int = 0): """The decoder's read: sinks β€– block-aligned window β€– opened members β€– concept summaries, one softmax. q [B,S,h,d], k/v [B,S,1,d], doc [B,S] (βˆ’1 = pad), sink [B,S] bool, ds [B,S] document starts. Returns [B,S,h,d]. `sum_len` > 0: the length scale (module docstring), log ρ added to every summary logit of the query. With the reasoner (`dv` [B,C,d] per concept, `dv_tok` [B,S,1,d] the same spread to the member tokens), every read from memory carries the reasoned update: summaries get ΞΌ_v + dv, and older tokens (previous block, sinks, opened members) get v + dv_tok. The query's own block is read from a second, raw copy of its keys and values: a token's update draws on its whole block, which is in the future of the queries inside that block. KV layout: [raw tokens with the update (S) β€– raw tokens, own block only (S, with the reasoner) β€– summaries (C)].""" pass # nn.exact_read: in this file B, S, h, d = q.shape g = k.shape[2] blk = cidx.block if cidx is not None else 512 use_sum = summaries and cidx is not None C = cidx.n_concepts if use_sum else 0 two = dv_tok is not None off_sum = 2 * S if two else S v1 = v + dv_tok.to(v.dtype) if two else v Ks, Vs = [k], [v1] if two: Ks.append(k) Vs.append(v) if use_sum: vs = cidx.mu_v if dv is None else cidx.mu_v + dv.to(cidx.mu_v.dtype) Ks.append(cidx.mu_k[:, :, None].to(k.dtype)) Vs.append(vs[:, :, None].to(v.dtype)) # The bias terms are read by flex's score_mod as captured buffers. They carry no gradient: a captured # buffer's gradient is accumulated with atomic adds, and every query and head adds into the same few # summary entries (E37 stage 0, 2026-11-07: 4Γ— slower than the LSA arm at 4k, 8.5Γ— at 16k with gradients # on them). The summaries' keys and values, which carry the read's gradient, are ordinary K / V entries. logn = torch.where(cidx.n > 0, cidx.n.clamp_min(1.0).log(), torch.zeros_like(cidx.n)).detach().contiguous() vhalf = ((0.5 * cidx.var) if variance else torch.zeros_like(cidx.var)).detach().contiguous() qn2 = ((q.detach().float() ** 2).sum(-1).transpose(1, 2) / d).contiguous() # [B, h, S] c_from = ((cidx.block_of + 2) * blk)[None].expand(B, -1).to(torch.int32).contiguous() c_doc = cidx.c_doc.to(torch.int32).contiguous() logrho = summary_log_scale(ds, S, blk, sum_len) if use_sum else None # [B, S] or None K, V = (torch.cat(Ks, dim=1), torch.cat(Vs, dim=1)) if len(Ks) > 1 else (k, v1) KV = K.shape[1] qt, kt, vt = (t.transpose(1, 2) for t in (q, K, V)) doc32 = doc.to(torch.int32) sk = sink.to(torch.int32) if backend == "flex": return _attend_concepts_flex(q, k, v, K=K, V=V, cidx=cidx, use_sum=use_sum, two=two, doc32=doc32, sk=sk, ds=ds, n_sinks=n_sinks, key_valid=key_valid, opened=opened, blk=blk, C=C, logn=logn if use_sum else None, vhalf=vhalf if use_sum else None, qn2=qn2 if use_sum else None, c_from=c_from if use_sum else None, c_doc=c_doc if use_sum else None, logrho=logrho) # reference path (CPU / MPS tests): the same rule as a dense mask and an additive bias if g != h: kt = kt.repeat_interleave(h // g, dim=1) vt = vt.repeat_interleave(h // g, dim=1) qi = torch.arange(S, device=q.device)[:, None] j = torch.arange(S, device=q.device)[None, :] own_lo = (qi // blk) * blk same = (doc[:, :, None] == doc[:, None, :]) & (doc[:, :, None] >= 0) keep = (j >= own_lo - blk)[None] | sink[:, None, :] if opened is not None: keep = keep | dense_open(opened.T, opened.index.codes, cap=opened.cap, raw_window=blk) if two: keep = keep & (j < own_lo)[None] eye = torch.eye(S, dtype=torch.bool, device=q.device)[None] mask = (j <= qi)[None] & same & keep if key_valid is not None: mask = mask & (key_valid.bool()[:, None, :] | eye) parts = [mask] if two: m2 = (j <= qi)[None] & same & (j >= own_lo)[None] if key_valid is not None: m2 = m2 & (key_valid.bool()[:, None, :] | eye) parts.append(m2) bias = torch.zeros(B, h, S, KV, device=q.device, dtype=torch.float32) if use_sum: cf = c_from.long() vis = ((qi >= cf[:, None, :]) & (cidx.c_doc[:, None, :] == doc[:, :, None]) & (doc[:, :, None] >= 0)) if opened is not None: vis = vis & ~(opened.T[:, :, :C].to(torch.int32) < int(opened.cap)) parts.append(vis) bias[..., off_sum:] = logn[:, None, None, :] + qn2[..., None] * vhalf[:, None, None, :] if logrho is not None: bias[..., off_sum:] += logrho[:, None, :, None] mask = torch.cat(parts, dim=-1) empty = ~mask.any(-1) # padding queries read nothing bias = bias.masked_fill(~(mask | empty[..., None])[:, None], float("-inf")) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=bias.to(qt.dtype)) return out.masked_fill(empty[:, None, :, None], 0.0).transpose(1, 2) def _attend_concepts_flex(q, k, v, *, K, V, cidx, use_sum, two, doc32, sk, ds, n_sinks, key_valid, opened, blk, C, logn, vhalf, qn2, c_from, c_doc, logrho=None): """Flex path in two calls merged by their log-sum-exp: (1) the raw tokens (window, sinks, opened members, and the own-block raw copy with the reasoner), no score_mod β€” the LSA arm's kernel shape; (2) the concept summaries only, with the bias in score_mod. One score_mod over the whole key range made the forward 4.4Γ— slower than the LSA arm (E37 stage 0, 2026-11-07): it gathers its buffers for every raw entry too. Exact: the merge is the single softmax over both. The length scale (`logrho` [B, S], one value per query) enters at the merge: adding log ρ to the summary call's log-sum-exp equals adding it to every summary logit.""" from torch.nn.attention.flex_attention import AuxRequest, create_block_mask pass # nn.exact_read: in this file pass # nn.perceiver_ar_lm: in this file B, S, h, d = q.shape g = k.shape[2] flex = _get_flex() nraw = 2 * S if two else S Kr, Vr = K[:, :nraw], V[:, :nraw] qt = q.transpose(1, 2).contiguous() term = open_term(opened.T, opened.index.codes, cap=opened.cap, raw_window=blk) if opened is not None else None def pred(b, hh, qi, j): own_lo = (qi // blk) * blk jr = torch.clamp(j, max=S - 1) same = (doc32[b, jr] == doc32[b, qi]) & (doc32[b, qi] >= 0) keep = (jr >= own_lo - blk) | (sk[b, jr] > 0) if term is not None: keep = keep | term(b, qi, jr) if two: keep = keep & (jr < own_lo) # own block: second copy ok = (jr <= qi) & same & keep & (j < S) if key_valid is not None: ok = ok & (key_valid[b, jr] | (jr == qi)) if two: j2 = torch.clamp(j - S, 0, S - 1) ok2 = ((j >= S) & (j2 <= qi) & (j2 >= own_lo) & (doc32[b, j2] == doc32[b, qi]) & (doc32[b, qi] >= 0)) if key_valid is not None: ok2 = ok2 & (key_valid[b, j2] | (j2 == qi)) ok = ok | ok2 return ok nqb = -(-S // 128) first_q = torch.arange(nqb, device=q.device) * 128 q_hi = torch.clamp(first_q + 127, max=S - 1) extra = [torch.stack([ds[:, first_q] // 128, torch.clamp(ds[:, first_q] + max(n_sinks - 1, 0), max=S - 1) // 128], dim=-1)] if opened is not None: extra.append(opened.extra_blocks()) if two: # the own block in the second copy: KV blocks from S + own-block start to S + the block's last query E = (blk + 127) // 128 + 2 lo = (S + (first_q // blk) * blk) // 128 hi = (S + q_hi) // 128 ids2 = lo[:, None] + torch.arange(E, device=q.device)[None] extra.append(torch.where(ids2 <= hi[:, None], ids2, torch.full_like(ids2, -1))[None].expand(B, -1, -1)) bm = _band_block_mask(pred, B=B, Q_LEN=S, KV_LEN=nraw, window=2 * blk, causal=True, device=q.device, extra_blocks=torch.cat(extra, dim=-1)) o1, aux1 = flex(qt, Kr.transpose(1, 2).contiguous(), Vr.transpose(1, 2).contiguous(), block_mask=bm, enable_gqa=(g != h), return_aux=AuxRequest(lse=True)) if not use_sum: return o1.transpose(1, 2) Ks, Vs = K[:, nraw:], V[:, nraw:] chosen = _chosen_lookup(opened) def spred(b, hh, qi, c): vis = (qi >= c_from[b, c]) & (c_doc[b, c] == doc32[b, qi]) & (doc32[b, qi] >= 0) if chosen is not None: vis = vis & ~chosen(b, qi, c) return vis def smod(score, b, hh, qi, c): return score + logn[b, c] + qn2[b, hh, qi] * vhalf[b, c] if S * C > _CHUNKED_MASK_PAIRS: bm2 = _chunked_block_mask(spred, B=B, Q_LEN=S, KV_LEN=C, device=q.device) else: bm2 = create_block_mask(spred, B=B, H=None, Q_LEN=S, KV_LEN=C, device=q.device, _compile=torch.cuda.is_available()) o2, aux2 = flex(qt, Ks.transpose(1, 2).contiguous(), Vs.transpose(1, 2).contiguous(), block_mask=bm2, score_mod=smod, enable_gqa=(g != h), return_aux=AuxRequest(lse=True)) l1, l2 = aux1.lse.float(), aux2.lse.float() # [B, h, S] if logrho is not None: l2 = l2 + logrho[:, None, :] # A padding query (document id βˆ’1, e.g. RULER's left padding and the generator's future slots) reads nothing in # either call: both lse are βˆ’inf, and an unguarded merge gave 0/0 = NaN there, which reached the real tokens # through 0 Γ— NaN in the next layers' attention tiles (E37 RULER, 2026-11-08: every answer garbage). It reads # zero, as flex gives the other arms' fully masked rows. m = torch.maximum(l1, l2) w1 = torch.where(torch.isfinite(l1), torch.exp(l1 - m), torch.zeros_like(l1)) w2 = torch.where(torch.isfinite(l2), torch.exp(l2 - m), torch.zeros_like(l2)) den = w1 + w2 out = (o1.float() * w1[..., None] + o2.float() * w2[..., None]) / den.clamp_min(1e-30)[..., None] out = torch.where((den > 0)[..., None], out, torch.zeros_like(out)) return out.to(q.dtype).transpose(1, 2) # ============================================================================================================== # nn/perceiver_ar_lm.py # ============================================================================================================== # Perceiver AR v2 β€” one global causal read, deep window-N stack, every token trained (E18). # # Family `perceiver_ar`, selected via `model_family=perceiver_ar` in the shared training # entrypoint. Spec: docs/experiments_specs/ahead/E18_perceiver_ar_v2_baseline.md. # # Training-time structure (all layers share one block; only the attention *pattern* differs): # # ids ─► tiny factorized embedding (e=256) + hashed 2/3-gram tables ─► MLP up-proj ─► x0 # ─► [swa(pre_window)] Γ— pre_layers # local pre-encoder: contextualize the history # ─► [full causal] Γ— global_layers # exclusive (E21) or raw (E18) global read+FFN # ─► [swa(block)] Γ— stack_layers # deep local processing over the last N tokens # ─► RMSNorm ─► chunked soft-capped lm_head + CE (+ z-loss) # # `par_mode="dense"` turns every layer into `full` with zero pre-layers (the matched control). # # Attention backends: `sdpa` (explicit boolean mask; reference / tests), `flex` # (torch.nn.attention.flex_attention block masks; default on Ampere), `flash` # (flash-attn varlen; Hopper fast path for packed inputs β€” wired, optional dependency). # # Hooks for the family (config fields only β€” no parameters unless enabled): # * `write_back_hook` (E19): a zero-init projection from latent states into the global # layer's K/V space, exposed via `prefix_kv()` / `global_kv_space` so latent thoughts and # agent messages (E21) can be appended to the prefix cache. # * `block_attention_mode` (E20): `causal` (E18) | `bidirectional` (block-diffusion adaptation). # * `message_boundary_token_id` / `message_compress_ratio` (E21): a reserved token splits a # row into sender | receiver. Local layers and n-gram tables treat the boundary as a # document start; the global read lets receivers see the prefix only as `KVCompressor` # slots (one per `ratio` tokens, in the read's own K/V space). Complete homogeneous # blocks only by default; `message_pool_remainder` also pools the incomplete last sender # block. `message_slots_inplace` writes slots into sender prefix positions (KV_LEN=S). # `message_inplace_raw_kv` (requires inplace) copies token K/V into those positions # instead of compressor slots; the exclusive `~replace` mask still hides uncompressed # remainder. `message_identity_slots` bypasses learned `u`/`delta` so each slot is a # frozen mean of the r tokens in the block (r=1: hard copy of token K/V after `k_norm`; # not last-token copy). `message_pack_stride` (default 0 = off) drops exclusive # leftover sender tokens vs N-token packs tiled to end at QUERY (left leftover # after BOS). r=1 identity otherwise keeps every sender token, so `--message_pool_remainder` # is a no-op at r=1; this flag is how incomplete leftover tokens are dropped vs kept # as identity slots (`message_pool_remainder` keeps them). E18-loadable. # `message_keep_local_swa` (default off) keeps exclusive slots on # the global read but does not treat QUERY as a SWA/n-gram document start β€” the local # window still sees raw prefix tokens that fall inside the sliding window. # `message_raw_window` (default 0 = full causal) limits the global read's raw keys to a # causal window of that many tokens, so the slots are the only long-range path and the # whole model is linear in length (the long-context length ladder). # `message_extra_slot_attends` (default 0) re-reads the *same* exclusive slot K/V # with queries updated by the previous hop β€” extra attends *inside one* Attention, # not a second global Block and not DNA `--hops`. Off by # default (`id=-1`) so E18 checkpoints stay byte-identical. # `global_layers` (default 1) is the count of sequential full Attention+FFN # blocks after the pre-encoder. `global_layers=2` is a second exclusive # (E21) or raw (E18) global read+FFN over that layer's own slot/prefix K/V β€” # distinct from `--stack_layers` (SWA) and from extra hops inside one Attention. # `message_update_slot_kv` (default off) rewrites exclusive slot K/V from the # post-attend residual before each extra hop (queries *and* slot keys update). # Extra=0 is unchanged either way; still not the full raw prefix. # `message_global_anchors` (default `none`) leaks a *sparse* set of extra # tokens into the exclusive global read. `query_nbhd`: a few sender tokens # immediately before QUERY (already r=1 replace slots). `query_side`: QUERY # itself plus a small window *after* the message boundary (receiver-side # type request; not prefix replace slots). `type_marks`: # `keymark`/`decoy`/`spanmark`/`hop`/`mark`. `key_spans` (E27): the DNA # *key* tokens after each sender `keymark` (not the mark, not `*val`). # Those positions join exclusive slot K/V as **raw** keys; at r>1 the # compressor does not overwrite them (identity `b` + pooled `a`). The rest # of the prefix stays exclusive (not E18 raw KV). `prefix_kv(as_message=True)` # returns those slots. # `message_prefix_ae` (E26, default off) adds a weak linear head that # reconstructs each complete sender block's token ids from that block's # slot. Compressor `u`/`delta` see AE gradients only when # `message_prefix_ae_stopgrad_answer` (default on) detaches slots on the # exclusive read. E18 checkpoints stay byte-identical with both flags off. # `message_write` (E30, default `block_mean`): `block_mean` is E21's # `KVCompressor`; `sw_perceiver` writes overlapping Perceiver banks # (`SlidingWindowPerceiverCompressor`, K learned queries per window, # stride < W, no mean residual). Concat exclusive path only. Off by # default so E18/E21 checkpoints stay byte-identical. # `message_write="latent_memory"` (E31): a separate writer branch (`nn/latent_memory.py`) # reads the token embeddings, writes `lm_latents` addressed latents per overlapping # window from two-way context (`lm_context`: page encoder | BiXT rounds) and hands them to # the global read as precomputed slots (`MessageCtx.slots`). The main path is unchanged. logger = logging.getLogger(__name__) # Sparse exclusive-plus-anchors (E21). Default `none` is prior exclusive slots. # `query_nbhd` = sender tokens immediately before QUERY (prefix; r=1 slots). # `query_side` = QUERY + window after the boundary (receiver; not prefix slots). # `key_spans` = DNA key-field tokens after each sender keymark (E27 hybrid b). MESSAGE_GLOBAL_ANCHORS = ( "none", "query_nbhd", "query_side", "type_marks", "query_nbhd+type", "key_spans", ) MESSAGE_QUERY_NBHD_DEFAULT = 4 # sender-before or QUERY-plus-after window MESSAGE_WRITES = ("block_mean", "sw_perceiver", "latent_memory") SWP_BANK_DEFAULT = 32 SWP_COVERAGE_DEFAULT = 8 SWP_OVERLAP_DEFAULT = 0.25 # stride = (1 - overlap) * window β†’ 192/256 in the notes # -------------------------------------------------------------------------------------- # Config # -------------------------------------------------------------------------------------- # PerceiverARConfig: see configuration_perceiver_ar.py (imported at the top of this file) # -------------------------------------------------------------------------------------- # Masks (single source of truth for every backend) # -------------------------------------------------------------------------------------- def make_mask_pred( pattern: str, window: int, key_valid: Optional[torch.Tensor], doc_ids: Optional[torch.Tensor], causal: bool = True, sink: bool = False, sink_pos: Optional[torch.Tensor] = None, ) -> Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor]: """Return mask_mod(b, h, q, kv) -> bool with FlexAttention semantics. Rules: causal (kv <= q) unless bidirectional; sliding window (q - kv < window) for `swa`; padded keys masked except the diagonal (keeps every query row non-empty); cross-document attention masked when `doc_ids` is given. With `sink=True` a `swa` query may additionally attend to its document's first token (`sink_pos[b, q]`, or position 0 when `sink_pos` is None): with RoPE that single extra key gives every windowed layer an absolute-position signal (qΒ·k_0 is a function of q's position) that a purely relative, windowed stack otherwise never has β€” needed for position-based retrieval such as copy at a fixed offset (E18 gate P2). """ def pred(b, h, q, kv): ok = (kv <= q) if causal else (kv >= 0) if pattern == "swa": dist = q - kv in_win = (dist < window) & (dist > -window) if sink: anchor = sink_pos[b, q] if sink_pos is not None else torch.zeros_like(q) in_win = in_win | (kv == anchor) ok = ok & in_win if key_valid is not None: ok = ok & (key_valid[b, kv] | (kv == q)) if doc_ids is not None: ok = ok & (doc_ids[b, q] == doc_ids[b, kv]) return ok return pred def dense_bool_mask( S: int, pattern: str, window: int, key_valid: Optional[torch.Tensor], doc_ids: Optional[torch.Tensor], device, causal: bool = True, batch: int = 1, sink: bool = False, sink_pos: Optional[torch.Tensor] = None, ) -> torch.Tensor: """[B,1,S,S] boolean mask (True = attend) β€” reference path used by `sdpa`.""" q = torch.arange(S, device=device)[:, None] kv = torch.arange(S, device=device)[None, :] ok = (kv <= q) if causal else torch.ones(S, S, dtype=torch.bool, device=device) if pattern == "swa": dist = q - kv in_win = (dist < window) & (dist > -window) if sink: if sink_pos is None: in_win = in_win | (kv == 0) else: anchor = (kv[None, None] == sink_pos[:, None, :, None]) # [B,1,S,S] in_win = in_win[None, None] | anchor ok = ok & in_win ok = ok[None, None].expand(batch, 1, S, S) if ok.dim() == 2 else ok.expand(batch, 1, S, S) if key_valid is not None: kv_ok = key_valid.bool()[:, None, None, :] | torch.eye(S, dtype=torch.bool, device=device)[None, None] ok = ok & kv_ok if doc_ids is not None: ok = ok & (doc_ids[:, None, :, None] == doc_ids[:, None, None, :]) return ok _FLEX_CACHE: dict = {} _flex_attention_fn = None def _get_flex(): global _flex_attention_fn if _flex_attention_fn is None: from torch.nn.attention.flex_attention import flex_attention if torch.cuda.is_available(): # Every (pattern, window) closure Γ— grad-mode Γ— batch/sequence shape is a separate # dynamo graph. The default cache_size_limit (8) is exceeded as soon as eval runs # next to training, and dynamo then silently falls back to EAGER flex_attention, # whose dense-math kernel materialises the SΓ—S scores (48 GB at 32k) β†’ OOM. # Cached decoding compiles one graph per prompt length and flex call (dynamic=False): e37a's two # calls a layer over 100 RULER documents at 128k passed 128 graphs at the 88th document (E37 # needles, 2026-11-14: frequent words OOM'd on the eager fallback). MC_DYNAMO_CACHE_LIMIT raises # the limit for such eval runs; the default (128) keeps training as it was. import os import torch._dynamo.config as dyn_cfg lim = int(os.environ.get("MC_DYNAMO_CACHE_LIMIT", "128")) dyn_cfg.cache_size_limit = max(int(getattr(dyn_cfg, "cache_size_limit", 8)), lim) if hasattr(dyn_cfg, "accumulated_cache_size_limit"): dyn_cfg.accumulated_cache_size_limit = max( int(dyn_cfg.accumulated_cache_size_limit), 1024, 8 * lim ) _flex_attention_fn = torch.compile(flex_attention, dynamic=False) else: _flex_attention_fn = flex_attention return _flex_attention_fn def _flex_block_mask(S, pattern, window, key_valid, doc_ids, device, causal, batch, sink=False, sink_pos=None): from torch.nn.attention.flex_attention import create_block_mask batch_dependent = key_valid is not None or doc_ids is not None or sink_pos is not None key = None if not batch_dependent: key = (S, pattern, window, causal, sink, str(device)) if key in _FLEX_CACHE: return _FLEX_CACHE[key] pred = make_mask_pred(pattern, window, key_valid, doc_ids, causal=causal, sink=sink, sink_pos=sink_pos) if pattern == "swa" and S * S > _CHUNKED_MASK_PAIRS: # Long rows: the band's block lists directly (O(S) work, not O(SΒ²) predicate calls). extra = None if sink: nqb = -(-S // 128) first_q = torch.arange(nqb, device=device) * 128 if sink_pos is not None: extra = (sink_pos[:, first_q] // 128)[..., None] else: extra = torch.zeros(batch, nqb, 1, dtype=torch.long, device=device) bm = _band_block_mask(pred, B=batch if batch_dependent or extra is not None else 1, Q_LEN=S, KV_LEN=S, window=window, causal=causal, device=device, extra_blocks=extra) if key is not None: _FLEX_CACHE[key] = bm return bm # Always compile the mask build on CUDA: the eager path materialises int64 (Q_LEN, KV_LEN) # index grids (~8 GB transient at 32k, impossible at 256k); the compiled path works # block by block. CPU keeps the eager path (no inductor cost in unit tests). bm = create_block_mask( pred, B=batch if batch_dependent else None, H=None, Q_LEN=S, KV_LEN=S, device=device, _compile=torch.cuda.is_available(), ) if key is not None: _FLEX_CACHE[key] = bm return bm # Above this many (query, key) pairs the global-read mask is built in query chunks: the # message predicate gathers per-token tags, and create_block_mask then materialises the full # bool (Q_LEN, KV_LEN) grid (29 GiB at 128k tokens + 109k slots) even when compiled. _CHUNKED_MASK_PAIRS = 1 << 30 def _chunked_block_mask(pred, *, B: int, Q_LEN: int, KV_LEN: int, device, block: int = 128, max_pairs: int = 1 << 29): """`create_block_mask` over query chunks of ≀ `max_pairs` (query, key) pairs, stitched with `BlockMask.from_kv_blocks`. Same mask; peak transient memory β‰ˆ `max_pairs` bytes.""" from torch.nn.attention.flex_attention import BlockMask, create_block_mask qc = max(block, (max_pairs // max(KV_LEN, 1)) // block * block) q0 = torch.zeros((), dtype=torch.int32, device=device) # captured tensor: no recompile per chunk def pred_c(b, h, q, kv): return pred(b, h, q + q0, kv) parts = [] for start in range(0, Q_LEN, qc): q0.fill_(start) n = min(qc, Q_LEN - start) bm = create_block_mask(pred_c, B=B, H=None, Q_LEN=n, KV_LEN=KV_LEN, device=device, BLOCK_SIZE=block, _compile=torch.cuda.is_available()) parts.append((bm.kv_num_blocks, bm.kv_indices, bm.full_kv_num_blocks, bm.full_kv_indices)) cat = [None if parts[0][i] is None else torch.cat([p[i] for p in parts], dim=2) for i in range(4)] return BlockMask.from_kv_blocks(cat[0], cat[1], cat[2], cat[3], BLOCK_SIZE=block, mask_mod=pred, seq_lengths=(Q_LEN, KV_LEN)) def _band_block_mask(mask_mod, *, B: int, Q_LEN: int, KV_LEN: int, window: int, causal: bool, device, extra_blocks: Optional[torch.Tensor] = None, block: int = 128): """Block mask for a mask that is zero outside a band `|q βˆ’ kv| < window` (plus optional extra KV blocks per query block, e.g. attention sinks or memory slots), built from the band geometry in O(blocks) instead of evaluating every (q, kv) pair. Every listed block is *partial*, so `mask_mod` still decides each entry: the mask is exact as long as the lists are a superset of the true non-zero blocks. `window <= 0` means unbounded (full causal). `extra_blocks` [B, n_q_blocks, E] int, βˆ’1 = unused.""" from torch.nn.attention.flex_attention import BlockMask nqb = -(-Q_LEN // block) nkb = -(-KV_LEN // block) qb = torch.arange(nqb, device=device) q_lo, q_hi = qb * block, torch.clamp(qb * block + block - 1, max=Q_LEN - 1) if window <= 0: lo = torch.zeros_like(qb) span = nqb else: lo = torch.clamp(q_lo - (window - 1), min=0) // block wb = -(-(window - 1) // block) span = wb + 2 if causal else 2 * wb + 3 hi_kv = q_hi if causal or window <= 0 else q_hi + (window - 1) hi = torch.clamp(hi_kv // block, max=nkb - 1) band = lo[:, None] + torch.arange(span, device=device)[None, :] band = torch.where(band <= hi[:, None], band, torch.full_like(band, -1)) cand = band[None].expand(B, nqb, span) if extra_blocks is not None: cand = torch.cat([cand, extra_blocks.to(cand.dtype)], dim=-1) big = torch.full_like(cand, nkb) cand = torch.where((cand >= 0) & (cand < nkb), cand, big) cand, _ = cand.sort(dim=-1) dup = torch.zeros_like(cand, dtype=torch.bool) dup[..., 1:] = cand[..., 1:] == cand[..., :-1] cand = torch.where(dup, big, cand) cand, _ = cand.sort(dim=-1) num = (cand < nkb).sum(-1).to(torch.int32) idx = torch.where(cand < nkb, cand, torch.zeros_like(cand)).to(torch.int32) # flex expects one column per KV block; valid entries are sorted first and number ≀ nkb idx = F.pad(idx, (0, nkb - idx.shape[-1])) if idx.shape[-1] < nkb else idx[..., :nkb] return BlockMask.from_kv_blocks(num[:, None], idx[:, None].contiguous(), None, None, BLOCK_SIZE=block, mask_mod=mask_mod, seq_lengths=(Q_LEN, KV_LEN)) def _message_extra_blocks(ctx: "MessageCtx", S: int, block: int = 128) -> Optional[torch.Tensor]: """Slot KV blocks for every query block that holds a receiver token (superset). Closed read (E31c): for each query block, the slot blocks holding a slot whose window closed at or before the block's last query.""" if ctx.override in ("none", "raw") or ctx.n_slots == 0: return None B = ctx.side.shape[0] nqb = -(-S // block) if ctx.read_rule == "closed": nb = ctx.n_slots big = torch.iinfo(torch.long).max close = torch.where((ctx.slot_doc >= 0) & (ctx.slot_close >= 0), ctx.slot_close, torch.full_like(ctx.slot_close, big)) # slot j is KV index S + j: align slots to KV blocks, then the earliest close per KV block first, last = S // block, (S + nb - 1) // block lead = S - first * block n_kb = last - first + 1 close = F.pad(close, (lead, n_kb * block - lead - nb), value=big).view(B, n_kb, block).amin(-1) q_hi = torch.clamp(torch.arange(nqb, device=close.device) * block + block - 1, max=S - 1) need = close[:, None, :] <= q_hi[None, :, None] # [B, nqb, n_kb] ids = torch.arange(first, last + 1, device=close.device) ex = ids[None, None, :].expand(B, nqb, n_kb) return torch.where(need, ex, torch.full_like(ex, -1)) pad = nqb * block - S side = F.pad(ctx.side, (0, pad), value=0) if pad else ctx.side has_recv = (side.view(B, nqb, block) >= 1).any(-1) # [B, nqb] first, last = S // block, (S + ctx.n_slots - 1) // block slot_blocks = torch.arange(first, last + 1, device=ctx.side.device) ex = slot_blocks[None, None, :].expand(B, nqb, slot_blocks.numel()) return torch.where(has_recv[..., None], ex, torch.full_like(ex, -1)) def attend( q: torch.Tensor, # [B,S,h,dh] k: torch.Tensor, # [B,S,g,dh] v: torch.Tensor, # [B,S,g,dh] *, pattern: str, window: int, key_valid: Optional[torch.Tensor], doc_ids: Optional[torch.Tensor], backend: str, causal: bool = True, cu_seqlens: Optional[torch.Tensor] = None, block_masks: Optional[dict] = None, sink: bool = False, sink_pos: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Attention with the E18 pattern semantics. Returns [B,S,h,dh]. `block_masks` is an optional per-forward memo for batch-dependent flex masks (padding or packed doc_ids): the same (pattern, window, causal) mask is shared by every layer of one forward (and its checkpoint recompute) instead of being rebuilt per layer. """ B, S, h, dh = q.shape g = k.shape[2] if backend == "flash": if sink and pattern == "swa": raise NotImplementedError("swa_sink is not expressible with flash-attn window_size; use flex") return _attend_flash(q, k, v, pattern, window, causal, cu_seqlens, key_valid) qt, kt, vt = (t.transpose(1, 2) for t in (q, k, v)) # [B,h/g,S,dh] if backend == "flex": memo_key = (pattern, window, causal, sink) if block_masks is not None and memo_key in block_masks: bm = block_masks[memo_key] else: bm = _flex_block_mask(S, pattern, window, key_valid, doc_ids, q.device, causal, B, sink=sink, sink_pos=sink_pos) if block_masks is not None: block_masks[memo_key] = bm qt, kt, vt = qt.contiguous(), kt.contiguous(), vt.contiguous() out = _get_flex()(qt, kt, vt, block_mask=bm, enable_gqa=(g != h)) return out.transpose(1, 2) # sdpa reference if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) if pattern == "full" and key_valid is None and doc_ids is None and causal: out = F.scaled_dot_product_attention(qt, kt, vt, is_causal=True) else: mask = dense_bool_mask(S, pattern, window, key_valid, doc_ids, q.device, causal, B, sink=sink, sink_pos=sink_pos) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask) return out.transpose(1, 2) def _attend_flash(q, k, v, pattern, window, causal, cu_seqlens, key_valid): try: from flash_attn import flash_attn_func, flash_attn_varlen_func except ImportError as e: # pragma: no cover raise RuntimeError("attn_backend='flash' requires the flash-attn package") from e win = (window - 1, 0 if causal else window - 1) if pattern == "swa" else (-1, -1) if cu_seqlens is None: if key_valid is not None and not bool(key_valid.all()): raise RuntimeError("flash backend needs packed inputs (no padding) or cu_seqlens") return flash_attn_func(q, k, v, causal=causal, window_size=win) B, S = q.shape[:2] max_len = int((cu_seqlens[1:] - cu_seqlens[:-1]).max()) out = flash_attn_varlen_func( q.reshape(B * S, *q.shape[2:]), k.reshape(B * S, *k.shape[2:]), v.reshape(B * S, *v.shape[2:]), cu_seqlens, cu_seqlens, max_len, max_len, causal=causal, window_size=win, ) return out.reshape(B, S, *out.shape[1:]) # -------------------------------------------------------------------------------------- # E21 message boundary: sender | receiver split of a row, prefix visible only as slots # -------------------------------------------------------------------------------------- TAG_SIDES = 64 # sides (boundary-separated parts) per document the global read's mask tag can hold @dataclass class MessageCtx: """Per-forward geometry of the E21 message boundary (built once in `_run_layers`). `side[b, t]` counts boundary tokens seen so far inside t's document (0 = sender, β‰₯ 1 = receiver). Local layers and the n-gram hashes treat a side change as a document start (`local_doc_ids`, unless `message_keep_local_swa`). On the global read a query may use raw keys only from its own side and, when it is a receiver, the compressed *slots* of every earlier side of its document. Slot `j` covers absolute positions [jΒ·r, (j+1)Β·r) for `message_write=block_mean`. For `sw_perceiver`, slots are `K` queries per overlapping window (`C = n_windowsΒ·K`); a mixed window keeps the earliest side. By default a block-mean slot is addressable only when the block is homogeneous in (document, side) β€” `slot_doc[b, j]` is that document (βˆ’1 otherwise). With `message_pool_remainder`, a mixed block still emits a slot from the first run of (doc, side) in that block (the incomplete last sender block next to QUERY). `anchor` [B,S] marks a sparse sender subset that joins exclusive slot K/V as raw keys (QUERY neighborhood and/or type marks). It is not the full prefix. `message_pack_stride>0` (remainder off) invalidates exclusive slots for the QUERY-aligned left leftover `[0, P % stride)` so incomplete leftover tokens are dropped rather than kept as r=1 identity slots. """ side: torch.Tensor # [B,S] int64 doc: torch.Tensor # [B,S] int64 β€” original document ids (pad / invalid = -1) local_doc_ids: torch.Tensor # [B,S] int64 β€” doc βŠ• side, fed to swa layers and the n-gram tables slot_doc: torch.Tensor # [B,nb] int64 slot_side: torch.Tensor # [B,nb] int64 slot_pos: torch.Tensor # [B,nb] int64 β€” RoPE position of each slot (its block's last token) n_sides: int = 0 # max(side) + 1 over the batch; 0 = derive lazily from `side` override: str = "real" # "real" | "none" | "swapped" | "raw" external: Optional[tuple[torch.Tensor, torch.Tensor]] = None # (kΜ„, vΜ„) given by a receiver-only forward pool_valid: Optional[torch.Tensor] = None # [B,S] tokens that enter compressor slots (remainder path) ratio: int = 1 # message_compress_ratio (scatter width for inplace) inplace: bool = False # True: slots overwrite sender prefix K/V; KV_LEN stays S inplace_raw_kv: bool = False # True: keep token K/V at replace positions (skip compressor) extra_slot_attends: int = 0 # extra exclusive attends over the frozen slot K/V (default 0) update_slot_kv: bool = False # rewrite exclusive slot K/V from post-attend residual anchor: Optional[torch.Tensor] = None # [B,S] bool β€” sparse raw keys joining exclusive slots anchor_mode: str = "none" slots: Optional[tuple[torch.Tensor, torch.Tensor]] = None # E31: precomputed (kΜ„, vΜ„), normed + RoPE'd slot_pos_lo: Optional[torch.Tensor] = None # "mixed" slot positions: the low-frequency pairs' position raw_window: int = 0 # >0: raw keys only within `q - j < raw_window` (linear-cost global layer) window_valid: Optional[torch.Tensor] = None # [B,n_w,W] per-window pool mask (E30 / E31) read_rule: str = "exclusive" # E31c "closed": any token reads slots of its document whose window closed ≀ it slot_close: Optional[torch.Tensor] = None # [B,nb] int64 β€” last token a slot's window wrote from (closed rule) slot_nope: bool = False # E31c "reader": slot keys are un-rotated and met by the un-rotated query note_topk: int = 0 # E33n: each query and head reads only its k best visible notes (0 = all) index: Optional[object] = None # E33p: nn.exact_read.NoteOpen (tied keys; what opens), built after the writer open_eval: str = "on" # E33p eval switch: "on" | "off" (no opened tokens) | "gist_off" (notes masked) # E33t: | "reuse" (a pass may re-open notes opened by earlier passes) open_seen: Optional[torch.Tensor] = None # E33t: [B,S,G] bool, notes each query opened in earlier passes index_losses: Optional[list] = None # E33t: index-loss terms of this forward (training) capture: Optional[dict] = None # exam probe: {"q_pos": [B,P]} β†’ appends each read's attention mass per note, # [B,P,nb] summed over heads, to capture["mass"] (`capture_note_mass`) # text multi-hop (2026-10-17), training only: per-round read targets [B,T,4] (answer position, round, first and # last token of the fact; βˆ’1 = padding), the round being read, the losses gathered, and the page geometry read_targets: Optional[torch.Tensor] = None read_round: int = 0 read_losses: Optional[list] = None page_starts: Optional[torch.Tensor] = None # [n_w] first token of each page page_window: int = 0 notes_per_page: int = 0 read_target: str = "page" # "page": any note of a page covering the span; "note": notes whose position is in it @property def n_slots(self) -> int: return int(self.slot_doc.shape[1]) def tag_stride(self) -> int: """Stride M of the (doc, side) β†’ `doc * M + side` tag. M = 2 Β· `TAG_SIDES` keeps the slot range test `0 < tag_q βˆ’ slot_tag < M/2` false for every other document and true exactly for an earlier side of the same document, for any row with at most `TAG_SIDES` sides per document (checked where sides are counted). A constant, not 2 Β· (max side + 1): under dynamic-shape compilation a data-dependent stride is a SymInt, and `div(tensor, SymInt)` does not trace inside the block-mask vmap. Rows with one side specialised to a constant, so E21 / E31c never hit it; E33f's question boundaries (up to ~13 sides) did (our GPU server, 16 Oct).""" return 2 * TAG_SIDES def tags(self) -> tuple[torch.Tensor, torch.Tensor]: """int32 `tag` [B,S] and `slot_tag` [B,nb]: `doc * M + side`, βˆ’1 for pad / invalid slots.""" m = self.tag_stride() tag = torch.where(self.doc < 0, torch.full_like(self.doc, -1), self.doc * m + self.side) slot_tag = torch.where(self.slot_doc < 0, torch.full_like(self.slot_doc, -1), self.slot_doc * m + self.slot_side) return tag.to(torch.int32), slot_tag.to(torch.int32) def build_message_anchors( input_ids: torch.Tensor, side: torch.Tensor, doc: torch.Tensor, *, mode: str, token_ids: tuple[int, ...] = (), window: int = MESSAGE_QUERY_NBHD_DEFAULT, key_len: int = 0, ) -> torch.Tensor: """Sparse extra positions that join exclusive slot K/V as raw keys. [B,S] bool. `type_marks`: control tokens in `token_ids` on the sender side (DNA keymark/decoy/ spanmark/hop, Glyph mark). `query_nbhd`: the `window` sender tokens immediately before each QUERY (document-start of side β‰₯ 1) β€” prefix, already r=1 replace slots. `query_side`: QUERY itself plus the next `window-1` receiver tokens (the SELECT type request lives here; not prefix replace slots). `key_spans`: the `key_len` sender tokens *after* each sender `keymark` (token_ids[0]); the mark itself and the value field are not marked. Default `none` is all-False. Count is << seq: a handful of marks and/or `window` tokens per QUERY, never the full prefix. """ B, S = input_ids.shape anchor = torch.zeros(B, S, dtype=torch.bool, device=input_ids.device) mode = mode or "none" if mode == "none": return anchor sender = (side == 0) & (doc >= 0) is_query = torch.zeros(B, S, dtype=torch.bool, device=input_ids.device) is_query[:, 0] = side[:, 0] >= 1 is_query[:, 1:] = (side[:, 1:] >= 1) & (side[:, :-1] == 0) if mode in ("type_marks", "query_nbhd+type") and token_ids: ids = torch.tensor(list(token_ids), device=input_ids.device, dtype=input_ids.dtype) is_mark = (input_ids.unsqueeze(-1) == ids).any(dim=-1) anchor = anchor | (is_mark & sender) if mode in ("query_nbhd", "query_nbhd+type") and int(window) > 0: w = int(window) nbhd = torch.zeros(B, S, dtype=torch.bool, device=input_ids.device) for d in range(1, w + 1): at_q = is_query[:, d:] same = doc[:, :-d] == doc[:, d:] nbhd[:, :-d] = nbhd[:, :-d] | (at_q & same) anchor = anchor | (nbhd & sender) if mode == "query_side" and int(window) > 0: w = int(window) nbhd = is_query.clone() for d in range(1, w): at_q = is_query[:, :-d] same = doc[:, d:] == doc[:, :-d] recv = side[:, d:] >= 1 nbhd[:, d:] = nbhd[:, d:] | (at_q & same & recv) anchor = anchor | nbhd if mode == "key_spans" and token_ids: n = int(key_len) if int(key_len) > 0 else 2 keymark = torch.as_tensor(int(token_ids[0]), device=input_ids.device, dtype=input_ids.dtype) is_mark = (input_ids == keymark) & sender span = torch.zeros(B, S, dtype=torch.bool, device=input_ids.device) for d in range(1, n + 1): at_mark = is_mark[:, :-d] same_doc = doc[:, d:] == doc[:, :-d] same_side = side[:, d:] == side[:, :-d] span[:, d:] = span[:, d:] | (at_mark & same_doc & same_side & sender[:, d:]) anchor = anchor | span return anchor def exclusive_visible(replace: torch.Tensor, ctx: MessageCtx) -> torch.Tensor: """In-place exclusive keys: slot replace positions βˆͺ sparse anchors.""" vis = replace if ctx.anchor is not None: vis = vis | ctx.anchor return vis _CLOSE_STRIDE = 1 << 22 # E31c closed read: slot code = doc Β· 2Β²Β² + close (int32: ≀ 4M tokens, ≀ 511 docs) def make_message_mask_pred(S: int, ctx: MessageCtx, key_valid: Optional[torch.Tensor], *, opened=None, gist: bool = True): """mask_mod over KV = raw keys [0, S) β€– slot keys [S, S + nb) for the global read. The predicate captures two int32 tag buffers rather than the four int64 buffers (`doc`, `side`, `slot_doc`, `slot_side`): every captured tensor is gathered into an integer tile inside the Triton template, and with head_dim 128 / bf16 the four int64 tiles push the kernel past the 99 KB shared-memory limit of sm86 (RTX 3090). With `tag = doc * M + side` (M = 2Β·n_sides), "same document and same side" is one equality and "same document, earlier side" is the range test `0 < tag_q βˆ’ slot_tag < n_sides`. `dense_message_mask` is the reference semantics. E33p: `opened(b, q, j)` (nn.exact_read.open_term) also lets query q read raw key j of its own document beyond the raw window; `gist=False` masks every slot (the "gist off" switch: opened tokens and window only). """ nb = ctx.n_slots m = ctx.tag_stride() n_sides = m // 2 tag, slot_tag = ctx.tags() raw_cross = ctx.override == "raw" slots_on = ctx.override not in ("none", "raw") and gist raw_window = int(ctx.raw_window or 0) anchor = ctx.anchor if anchor is None: anchor = torch.zeros(tag.shape, dtype=torch.bool, device=tag.device) closed = ctx.read_rule == "closed" if closed: # E31c: one int32 per slot, doc Β· S + close (no extra captured tensor; see the docstring) if ctx.slot_close is None: raise RuntimeError("the closed read needs ctx.slot_close") # The packing stride is a fixed power of two, not S: under dynamic-shape compilation S is a SymInt # and `div(tensor, SymInt)` does not trace (it broke flex at varying eval lengths on CUDA). n_doc = int(ctx.slot_doc.max().item()) + 1 if ctx.slot_doc.numel() else 1 if S > _CLOSE_STRIDE or max(n_doc, 1) * _CLOSE_STRIDE >= 2**31: raise ValueError(f"closed read: {n_doc} documents Γ— {S} tokens overflow the int32 slot code " f"(≀ {_CLOSE_STRIDE} tokens, ≀ {2**31 // _CLOSE_STRIDE - 1} documents per row)") slot_tag = torch.where((ctx.slot_doc < 0) | (ctx.slot_close < 0), torch.full_like(ctx.slot_doc, -1), ctx.slot_doc * _CLOSE_STRIDE + ctx.slot_close).to(torch.int32) def pred(b, h, q, kv): is_raw = kv < S j = torch.where(is_raw, kv, kv - S) js = torch.clamp(j, max=max(nb - 1, 0)) jr = torch.clamp(j, max=S - 1) # raw lookups only (a slot index can exceed S: short rows, many notes) tq = tag[b, q] tj = tag[b, jr] same_doc = torch.div(tj, m, rounding_mode="floor") == torch.div(tq, m, rounding_mode="floor") if raw_cross: same = same_doc else: same = tj == tq causal_same = (j <= q) & same raw_ok = causal_same if raw_window > 0: raw_ok = raw_ok & (q - j < raw_window) if opened is not None: raw_ok = raw_ok | (causal_same & opened(b, q, jr)) if not raw_cross: dq = torch.div(tq, m, rounding_mode="floor") sq = tq - dq * m anc = is_raw & (tq >= 0) & (tj >= 0) & (sq >= 1) & anchor[b, jr] & same_doc raw_ok = raw_ok | anc if key_valid is not None: raw_ok = raw_ok & (key_valid[b, jr] | (j == q)) if not slots_on: return raw_ok & is_raw s = slot_tag[b, js] if closed: dq = torch.div(tq, m, rounding_mode="floor") s_doc = torch.div(s, _CLOSE_STRIDE, rounding_mode="floor") slot_ok = (j < nb) & (s >= 0) & (tq >= 0) & (s_doc == dq) & (s - s_doc * _CLOSE_STRIDE <= q) else: d = tq - s slot_ok = (j < nb) & (s >= 0) & (d > 0) & (d < n_sides) return torch.where(is_raw, raw_ok, slot_ok) return pred def dense_message_mask(S: int, ctx: MessageCtx, key_valid: Optional[torch.Tensor], device, *, opened: Optional[torch.Tensor] = None, gist: bool = True) -> torch.Tensor: """[B,1,S,S+nb] boolean mask (True = attend) β€” reference path used by `sdpa`. E33p: `opened` [B,S,S] bool (nn.exact_read.dense_open) adds raw keys beyond the window for the same document and side; `gist=False` masks every slot.""" side, doc = ctx.side, ctx.doc B = side.shape[0] q = torch.arange(S, device=device)[:, None] j = torch.arange(S, device=device)[None, :] causal = (j <= q) & (q - j < ctx.raw_window) if ctx.raw_window else (j <= q) causal_doc = causal[None, None] & (doc[:, None, :, None] == doc[:, None, None, :]) if opened is not None: causal_doc = causal_doc | ((j <= q)[None, None] & (doc[:, None, :, None] == doc[:, None, None, :]) & opened[:, None]) if ctx.override == "raw": raw = causal_doc else: same_side = side[:, None, :, None] == side[:, None, None, :] raw = causal_doc & same_side if ctx.anchor is not None: # Receiver queries may read anchored keys as extra exclusive raw # (sender type_marks / query_nbhd, or QUERY-side query_side). Still # causal + same-document; not the full prefix. anc = (side[:, None, :, None] >= 1) & ctx.anchor[:, None, None, :] raw = raw | (causal_doc & anc) if key_valid is not None: raw = raw & (key_valid.bool()[:, None, None, :] | torch.eye(S, dtype=torch.bool, device=device)[None, None]) if ctx.read_rule == "closed": # E31c: every token reads its document's windows closed at or before it slot = ( (doc[:, None, :, None] >= 0) & (ctx.slot_doc[:, None, None, :] >= 0) & (ctx.slot_doc[:, None, None, :] == doc[:, None, :, None]) & (ctx.slot_close[:, None, None, :] >= 0) & (ctx.slot_close[:, None, None, :] <= q[None, None]) ) else: slot = ( (side[:, None, :, None] >= 1) & (ctx.slot_doc[:, None, None, :] >= 0) & (ctx.slot_doc[:, None, None, :] == doc[:, None, :, None]) & (ctx.slot_side[:, None, None, :] < side[:, None, :, None]) ) if ctx.override in ("none", "raw") or not gist: slot = torch.zeros_like(slot) return torch.cat([raw.expand(B, 1, S, S), slot], dim=-1) def mix_inplace_kv(k, v, k_bar, v_bar, ctx: MessageCtx): """Scatter slot K/V onto sender positions covered by a valid complete block. `k`/`v` and `k_bar`/`v_bar` are un-RoPE'd. Returns mixed K/V at length S and `replace` [B,S] (True = this prefix position holds a slot, not uncompressed sender KV). When `ctx.inplace_raw_kv`, keep token K/V at those positions (skip compressor values) and still return the same `replace` mask so receivers cannot see uncompressed remainder. """ B, S, g, dh = k.shape r = max(int(ctx.ratio), 1) valid_tok = (ctx.slot_doc >= 0).repeat_interleave(r, dim=1)[:, :S] replace = valid_tok & (ctx.side == 0) & (ctx.doc >= 0) write = replace # E27: at r>1 keep raw token K/V on key-span anchors (identity b); r=1 identity # slots already are raw keys, so do not punch holes in the replace mask. if ctx.anchor is not None and r > 1 and bool(ctx.anchor.any()): write = replace & ~ctx.anchor if getattr(ctx, "inplace_raw_kv", False): return k, v, replace k_exp = k_bar.repeat_interleave(r, dim=1)[:, :S] v_exp = v_bar.repeat_interleave(r, dim=1)[:, :S] k_mix = torch.where(write[..., None, None], k_exp.to(k.dtype), k) v_mix = torch.where(write[..., None, None], v_exp.to(v.dtype), v) return k_mix, v_mix, write def dense_inplace_mask(S: int, ctx: MessageCtx, key_valid: Optional[torch.Tensor], replace: torch.Tensor, device) -> torch.Tensor: """[B,1,S,S] β€” causal same-document (raw geometry) minus uncompressed sender leaks.""" side, doc = ctx.side, ctx.doc q = torch.arange(S, device=device)[:, None] j = torch.arange(S, device=device)[None, :] raw = (j <= q)[None, None] & (doc[:, None, :, None] == doc[:, None, None, :]) if key_valid is not None: raw = raw & (key_valid.bool()[:, None, None, :] | torch.eye(S, dtype=torch.bool, device=device)[None, None]) recv = (side >= 1)[:, None, :, None] send = (side == 0)[:, None, None, :] leak = recv & send & (~replace[:, None, None, :]) return raw & ~leak def make_inplace_mask_pred(S: int, ctx: MessageCtx, key_valid: Optional[torch.Tensor], replace: torch.Tensor): """mask_mod over KV length S for the in-place exclusive read.""" m = ctx.tag_stride() tag, _ = ctx.tags() def pred(b, h, q, kv): tq = tag[b, q] tj = tag[b, kv] same_doc = torch.div(tj, m, rounding_mode="floor") == torch.div(tq, m, rounding_mode="floor") raw_ok = (kv <= q) & same_doc if key_valid is not None: raw_ok = raw_ok & (key_valid[b, kv] | (kv == q)) leak = (ctx.side[b, q] >= 1) & (ctx.side[b, kv] == 0) & (~replace[b, kv]) return raw_ok & ~leak return pred def attend_inplace(q, k, v, *, ctx: MessageCtx, replace, key_valid, backend, block_masks=None): """Global read over in-place mixed K/V (length S). Returns [B,S,h,dh].""" B, S, h, dh = q.shape g = k.shape[2] if backend == "flash": raise NotImplementedError("message boundary needs flex or sdpa") visible = exclusive_visible(replace, ctx) qt, kt, vt = (t.transpose(1, 2) for t in (q, k, v)) if backend == "flex": from torch.nn.attention.flex_attention import create_block_mask memo_key = ("message_inplace", ctx.override, ctx.n_slots, getattr(ctx, "anchor_mode", "none")) if block_masks is not None and memo_key in block_masks: bm = block_masks[memo_key] else: pred = make_inplace_mask_pred(S, ctx, key_valid, visible) bm = create_block_mask(pred, B=B, H=None, Q_LEN=S, KV_LEN=S, device=q.device, _compile=torch.cuda.is_available()) if block_masks is not None: block_masks[memo_key] = bm qt, kt, vt = qt.contiguous(), kt.contiguous(), vt.contiguous() out = _get_flex()(qt, kt, vt, block_mask=bm, enable_gqa=(g != h)) return out.transpose(1, 2) if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) mask = dense_inplace_mask(S, ctx, key_valid, visible, q.device) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask) return out.transpose(1, 2) class KVCompressor(nn.Module): """One message slot per `ratio` prefix tokens, in the global read's K/V space (E21 / E18c). Slot = attention-pooled block: weights softmax_j(h_j Β· u_g) per kv-head (u zero-init β†’ uniform = mean pool), keys pooled *before* `k_norm`, plus a zero-init linear correction from the block's mean hidden state. At init this is exact mean pooling; with `ratio=1` every slot is one token's K/V exactly (the uncompressed arm U) *until* `u`/`delta` move. `identity_slots` bypasses `u`/`delta` for a frozen mean of valid tokens in each block of `r` (r=1: hard copy of `k_norm(k_raw)`, `v`; r>1: not last-token copy). RoPE is applied by the caller at the slot's position. """ def __init__(self, cfg: PerceiverARConfig): super().__init__() self.ratio = int(cfg.message_compress_ratio) self.g, self.dh = cfg.num_kv_heads, cfg.head_dim self.identity_slots = bool(getattr(cfg, "message_identity_slots", False)) self.u = nn.Parameter(torch.zeros(self.g, cfg.hidden_size)) self.delta = nn.Linear(cfg.hidden_size, 2 * self.g * self.dh, bias=False) nn.init.zeros_(self.delta.weight) def participation(self) -> torch.Tensor: """Keep compressor params in the graph when a batch has no QUERY (DDP).""" return self.u.sum() + self.delta.weight.sum() def n_slots(self, S: int) -> int: return -(-S // self.ratio) def forward(self, h, k_raw, v, k_norm, valid: Optional[torch.Tensor] = None): """h [B,S,d] (attn-normed block input), k_raw/v [B,S,g,dh] (k before k_norm) β†’ (kΜ„, vΜ„) each [B,nb,g,dh]; `valid` [B,S] excludes tokens from the pooling.""" B, S, d = h.shape r, g, dh = self.ratio, self.g, self.dh nb = self.n_slots(S) pad = nb * r - S if pad: h = F.pad(h, (0, 0, 0, pad)) k_raw = F.pad(k_raw, (0, 0, 0, 0, 0, pad)) v = F.pad(v, (0, 0, 0, 0, 0, pad)) ok = torch.ones(B, S, dtype=torch.bool, device=h.device) if valid is None else valid.bool() if pad: ok = F.pad(ok, (0, pad), value=False) ok = ok.view(B, nb, r) if self.identity_slots: w = ok.to(dtype=k_raw.dtype) w = w / w.sum(dim=2, keepdim=True).clamp(min=1) k_bar = torch.einsum("bnr,bnrgd->bngd", w, k_raw.view(B, nb, r, g, dh)) v_bar = torch.einsum("bnr,bnrgd->bngd", w, v.view(B, nb, r, g, dh)) z = (self.u.sum() + self.delta.weight.sum()).to(k_bar.dtype) * 0.0 return k_norm(k_bar) + z, v_bar + z hb = h.view(B, nb, r, d) scores = torch.einsum("bnrd,gd->bnrg", hb, self.u.to(hb.dtype)) scores = scores.masked_fill(~ok[..., None], float("-inf")) w = torch.softmax(scores.float(), dim=2) w = torch.nan_to_num(w, nan=0.0).to(hb.dtype) k_bar = torch.einsum("bnrg,bnrgd->bngd", w, k_raw.view(B, nb, r, g, dh)) v_bar = torch.einsum("bnrg,bnrgd->bngd", w, v.view(B, nb, r, g, dh)) cnt = ok.sum(dim=2, keepdim=True).clamp(min=1).to(hb.dtype) h_mean = (hb * ok[..., None].to(hb.dtype)).sum(dim=2) / cnt dk, dv = self.delta(h_mean).view(B, nb, 2, g, dh).unbind(dim=2) return k_norm(k_bar) + dk, v_bar + dv # -------------------------------------------------------------------------------------- # E30: overlapping Perceiver banks (learned queries, no mean residual) # -------------------------------------------------------------------------------------- @dataclass(frozen=True) class SWPGeometry: """Length-scaling window banks. `n_slots = n_windows * bank_size` (C ∝ N).""" bank_size: int window: int stride: int n_windows: int starts: tuple[int, ...] n_slots: int n_heads: int query_dim: int coverage: float compression: float sliding: bool # n_windows >= 2 β€” the sliding claim is live def swp_resolved_heads(cfg: PerceiverARConfig) -> tuple[int, int]: """(n_heads, query_dim) for the write. Count first; width is scoring bandwidth. Do not gcd-drop below 4 heads when `query_dim` is not divisible (H=384, 6 Q heads, qdim=128 would otherwise silently become 2 heads). Derived head counts snap to a β‰₯4 divisor of qdim; an explicit `--swp_n_heads` keeps the count and rounds qdim up. """ requested = int(getattr(cfg, "swp_n_heads", 0) or 0) n_heads = requested if requested > 0 else max(4, int(cfg.num_attention_heads)) qdim = int(getattr(cfg, "swp_query_dim", 0) or 0) if qdim <= 0: qdim = max(int(cfg.head_dim), 4 * int(cfg.token_embedding_dim)) if qdim % n_heads == 0: return n_heads, qdim if requested <= 0: for h in (8, 4): if qdim % h == 0: return h, qdim qdim = ((qdim + n_heads - 1) // n_heads) * n_heads return n_heads, qdim def _swp_window_starts(seq_len: int, window: int, stride: int) -> tuple[int, ...]: S = int(seq_len) W = min(max(int(window), 1), max(S, 1)) st = max(1, int(stride)) if S <= W: return (0,) starts = list(range(0, S - W + 1, st)) last = S - W if starts[-1] != last: starts.append(last) # unique, still increasing (last is always β‰₯ the range's final start) return tuple(dict.fromkeys(starts)) def swp_geometry(cfg: PerceiverARConfig, seq_len: int) -> SWPGeometry: """Derive (K, W, stride, windows) for this length. Canonical: K=32, W=8K, stride=0.75 W (notes: 256 / 192). On short sequences auto-fit halves K until at least two windows exist, keeping coverage β‰ˆ 8. Parameter tensors stay at `swp_bank_size`; unused queries are dummy-summed. """ bank_max = max(1, int(getattr(cfg, "swp_bank_size", SWP_BANK_DEFAULT) or SWP_BANK_DEFAULT)) coverage = max(1, int(getattr(cfg, "swp_coverage", SWP_COVERAGE_DEFAULT) or SWP_COVERAGE_DEFAULT)) pinned_w = int(getattr(cfg, "swp_window", 0) or 0) pinned_st = int(getattr(cfg, "swp_stride", 0) or 0) auto = bool(getattr(cfg, "swp_auto_fit", True)) S = max(int(seq_len), 1) K = bank_max n_heads, qdim = swp_resolved_heads(cfg) def _pack(k: int) -> tuple[int, int, tuple[int, ...]]: w = pinned_w if pinned_w > 0 else coverage * k w = min(max(w, 1), S) st = pinned_st if pinned_st > 0 else max(1, int(round(w * (1.0 - SWP_OVERLAP_DEFAULT)))) st = max(1, min(st, w)) starts = _swp_window_starts(S, w, st) return w, st, starts W, stride, starts = _pack(K) if auto and pinned_w <= 0: while len(starts) < 2 and K > 1: K = max(1, K // 2) W, stride, starts = _pack(K) n_w = len(starts) n_slots = n_w * K return SWPGeometry( bank_size=K, window=W, stride=stride, n_windows=n_w, starts=starts, n_slots=n_slots, n_heads=n_heads, query_dim=qdim, coverage=W / max(K, 1), compression=S / max(n_slots, 1), sliding=n_w >= 2, ) class SlidingWindowPerceiverCompressor(nn.Module): """K learned queries per overlapping window, pooling token K/V (E30). Slot = attention-weighted sum of the window's `k_raw`/`v` β€” a filter, not a mean. No residual mean, no slot–slot mixer. Queries that auto-fit does not use still participate via `participation()` so DDP stays happy. """ def __init__(self, cfg: PerceiverARConfig): super().__init__() self.bank_max = max(1, int(getattr(cfg, "swp_bank_size", SWP_BANK_DEFAULT) or SWP_BANK_DEFAULT)) self.g, self.dh = cfg.num_kv_heads, cfg.head_dim self.cfg_ref = cfg n_heads, qdim = swp_resolved_heads(cfg) self.n_heads, self.query_dim = n_heads, qdim self.dh_q = qdim // n_heads self.norm = nn.RMSNorm(cfg.hidden_size) self.q = nn.Parameter(torch.randn(self.bank_max, n_heads, self.dh_q) * cfg.init_std) self.wk = nn.Linear(cfg.hidden_size, n_heads * self.dh_q, bias=False) self.q_norm = nn.RMSNorm(self.dh_q) self.k_norm_q = nn.RMSNorm(self.dh_q) # Flat so Muon treats it as a bias, matching ConceptPooler.pos_bias. max_w = max(self.bank_max * max(1, int(getattr(cfg, "swp_coverage", SWP_COVERAGE_DEFAULT) or SWP_COVERAGE_DEFAULT)), int(getattr(cfg, "swp_window", 0) or 0), 1) self.pos_bias = nn.Parameter(torch.zeros(max_w * n_heads)) self._last_entropy = None self._last_geometry = None def geometry(self, S: int) -> SWPGeometry: return swp_geometry(self.cfg_ref, S) def n_slots(self, S: int) -> int: return self.geometry(S).n_slots def participation(self) -> torch.Tensor: return self.q.sum() + self.wk.weight.sum() + self.pos_bias.sum() def slot_positions(self, pos: torch.Tensor) -> torch.Tensor: """pos [B,S] β†’ slot RoPE positions [B,C] (page centres inside each window).""" B, S = pos.shape geo = self.geometry(S) device = pos.device starts = torch.tensor(geo.starts, device=device, dtype=torch.long) page = max(geo.window // max(geo.bank_size, 1), 1) qix = torch.arange(geo.bank_size, device=device) off = (qix + 1) * page - 1 idx = (starts[:, None] + off[None, :]).clamp(0, S - 1).reshape(-1) return pos.index_select(1, idx) def forward(self, h, k_raw, v, k_norm, valid: Optional[torch.Tensor] = None, window_valid: Optional[torch.Tensor] = None): """h [B,S,d], k_raw/v [B,S,g,dh] β†’ (kΜ„, vΜ„) [B,C,g,dh]. `window_valid` [B,n_w,W] is the per-window pooling rule (own earliest side, one document). When given it replaces the global `valid` mask, which let a window pool tokens that were only poolable in *another* window (a future-token leak).""" B, S, d = h.shape geo = self.geometry(S) self._last_geometry = geo n_w, W, K = geo.n_windows, geo.window, geo.bank_size H, dh_q = self.n_heads, self.dh_q g, dh = self.g, self.dh device = h.device starts = torch.tensor(geo.starts, device=device, dtype=torch.long) tok = starts[:, None] + torch.arange(W, device=device) in_range = tok < S tok = tok.clamp(max=max(S - 1, 0)) ok = in_range[None].expand(B, n_w, W) if window_valid is not None: ok = ok & window_valid.bool() elif valid is not None: ok = ok & valid.bool()[:, tok] hn = self.norm(h) hb = hn[:, tok] # [B, n_w, W, d] k_win = k_raw[:, tok] # [B, n_w, W, g, dh] v_win = v[:, tok] k_s = self.k_norm_q(self.wk(hb).view(B, n_w, W, H, dh_q)) q = self.q_norm(self.q[:K]) # [K, H, dh_q] logits = torch.einsum("khd,bnwhd->bnkhw", q, k_s) / math.sqrt(dh_q) bias = self.pos_bias[: W * H].view(W, H).t() # [H, W] logits = logits + bias[None, None, None] logits = logits.masked_fill(~ok[:, :, None, None, :], float("-inf")) w_h = torch.softmax(logits.float(), dim=-1) w_h = torch.nan_to_num(w_h, nan=0.0) w = w_h.mean(dim=3).to(k_raw.dtype) # [B, n_w, K, W] live = ok.any(dim=-1) # [B, n_w] w = w * live[:, :, None, None].to(w.dtype) k_bar = torch.einsum("bnkw,bnwgd->bnkgd", w, k_win) v_bar = torch.einsum("bnkw,bnwgd->bnkgd", w, v_win) k_bar = k_bar.reshape(B, n_w * K, g, dh) v_bar = v_bar.reshape(B, n_w * K, g, dh) # unused auto-fit tail (queries, pos_bias beyond W) stays in the graph for DDP extra_q = self.q[K:].sum() if K < self.bank_max else self.q.sum() * 0.0 used_b = W * H extra_b = self.pos_bias[used_b:].sum() if used_b < self.pos_bias.numel() else self.pos_bias.sum() * 0.0 z = (extra_q + extra_b).to(k_bar.dtype) * 0.0 # entropy of the token distribution (diagnostic: smear β‰ˆ log W) w_tok = w.clamp(min=0) w_tok = w_tok / w_tok.sum(dim=-1, keepdim=True).clamp(min=1e-12) ent = -(w_tok * (w_tok + 1e-12).log()).sum(dim=-1) live_f = live[:, :, None].expand_as(ent) if bool(live_f.any()): self._last_entropy = float(ent[live_f].mean().detach()) else: self._last_entropy = float("nan") return k_norm(k_bar) + z, v_bar + z class PrefixAEHead(nn.Module): """Weak linear reconstruction of each r-token block from its slot K (E26).""" def __init__(self, g: int, dh: int, r: int, vocab: int): super().__init__() self.r = int(r) self.vocab = int(vocab) self.proj = nn.Linear(g * dh, self.r * vocab, bias=False) def forward(self, k_bar: torch.Tensor) -> torch.Tensor: """k_bar [B,nb,g,dh] β†’ logits [B,nb,r,V].""" B, nb, g, dh = k_bar.shape return self.proj(k_bar.reshape(B, nb, g * dh)).view(B, nb, self.r, self.vocab) def note_age_bias(pos: torch.Tensor, slot_pos: torch.Tensor, slope: torch.Tensor, unit: float, mode: str) -> torch.Tensor: """E33d: additive score bias on the note columns, [B,h,S,C] (fp32). bias[b,h,t,c] = βˆ’slope[h] Β· f(max(0, pos[b,t] βˆ’ slot_pos[b,c]) / unit), f = log1p ("log") or identity ("linear"). `pos` [B,S] are the readers' positions in their documents, `slot_pos` [B,C] each note's read position (the writer's expected position of what its latent read).""" age = (pos.to(torch.float32)[:, :, None] - slot_pos.to(torch.float32)[:, None, :]).clamp(min=0.0) / float(unit) f = torch.log1p(age) if mode == "log" else age return -slope.to(torch.float32)[None, :, None, None] * f[:, None] def note_rank_logcount(q_slot: torch.Tensor, k_bar: torch.Tensor, ctx: "MessageCtx", *, scale: float, rep: int, margin: float, sharp: float, chunk: int = 1024, gate_heads: Optional[list] = None) -> torch.Tensor: """E33e: how many NEWER notes match the reader about as well as its best note, per page, [B,h,S,n_w] fp32. For reader t, head h and visible note c (same document, page closed at or before t β€” the closed read), l = q_slotΒ·kΜ„ Β· scale is the read's own note score and m the best visible score. The match gate is Οƒ(sharp Β· (l βˆ’ m + margin)); a page's count is the summed gate over the visible notes of every strictly newer page (later close), and the returned value is log(1 + count). A lone fact has no newer match, so it keeps its score at any length; among several matches (Anna's ten moves) the newest gets 0, the one before it β‰ˆ log 2, … β€” an order that does not grow with the document. Computed without gradient (the read's scores are trained by the read itself); only the per-head strength in front of it learns. `rep` = notes per page (latents Γ— reader tokens): the pages are the n_w = C / rep groups of the slot axis. `gate_heads` (E33g2): the match is the MEAN score of these heads (the content heads that find the asked person's facts) and every head gets that one count β€” so the order heads rank the asked person's notes, not anyone's.""" B, S, h, dh = q_slot.shape C, g = k_bar.shape[1], k_bar.shape[2] n_w = C // rep with torch.no_grad(): sd, sc = ctx.slot_doc, ctx.slot_close # [B,C] wclose = sc.view(B, n_w, rep)[..., 0] # every note of a page shares its close newer = (wclose[:, :, None] > wclose[:, None, :]).float() # [B, w', w]: page w' is newer than page w kbh = k_bar.float().repeat_interleave(h // g, dim=2) # [B,C,h,dh] tpos = torch.arange(S, device=q_slot.device) out = torch.zeros(B, h, S, n_w, dtype=torch.float32, device=q_slot.device) for s0 in range(0, S, chunk): s1 = min(S, s0 + chunk) vis = ((sd[:, None, :] >= 0) & (sd[:, None, :] == ctx.doc[:, s0:s1, None]) & (sc[:, None, :] >= 0) & (sc[:, None, :] <= tpos[None, s0:s1, None])) # [B,s,C] l = torch.einsum("bshd,bchd->bhsc", q_slot[:, s0:s1].float(), kbh) * scale l = l.masked_fill(~vis[:, None], float("-inf")) if gate_heads: l = l[:, gate_heads].masked_fill(~vis[:, None], 0.0).mean(1, keepdim=True) l = l.masked_fill(~vis[:, None], float("-inf")) m = l.amax(-1, keepdim=True) m = torch.where(torch.isfinite(m), m, torch.zeros_like(m)) gate = torch.sigmoid(sharp * (l - m + margin)) # exactly 0 on invisible notes gw = gate.view(B, l.shape[1], s1 - s0, n_w, rep).sum(-1) out[:, :, s0:s1] = torch.log1p(torch.einsum("bhsk,bkw->bhsw", gw, newer)) # one gate head broadcasts return out @torch.no_grad() def score_notes(qs: torch.Tensor, raw_lse: torch.Tensor, k_bar: torch.Tensor) -> torch.Tensor: """Agent A's side of a request: B's note queries `qs` [B,P,h,dh] and raw log-totals `raw_lse` [B,P,h] (from `capture_note_mass`) against A's notebook keys `k_bar` [B,nb,g,dh] β†’ each note's share of B's read, summed over heads, [B,P,nb] β€” the same numbers `capture_note_mass` gives with the whole notebook visible.""" rep = qs.shape[2] // k_bar.shape[2] sl = torch.einsum("bphd,bchd->bphc", qs.float(), k_bar.float().repeat_interleave(rep, dim=2)) * qs.shape[-1] ** -0.5 lse = torch.logsumexp(torch.cat([raw_lse.float()[..., None], sl], -1), -1, keepdim=True) return torch.exp(sl - lse).sum(2) @torch.no_grad() def capture_note_mass(q, k, k_bar, ctx: MessageCtx, key_valid, *, q_slot=None) -> None: """Notes-budget exam: the share of each note in this read's attention, at the query positions `ctx.capture["q_pos"]` [B,P], summed over heads β†’ appended to `ctx.capture["mass"]` as [B,P,nb] (one entry per read: a looped model appends one per round). The softmax is the read's own: raw keys in the raw window β€– the notes this query may see, logits qΒ·k and q_slotΒ·kΜ„ (or qΒ·kΜ„) at scale 1/√dh. The E33d / E33e note terms are not included. With `_note_keep` set, the notes this query could see in the whole notebook are scored (`capture["slot_close_all"]`), hidden ones included: what agent A computes when B sends this query (B adds its raw-key total per head).""" cap = ctx.capture if cap.get("slot_close_all") is not None: ctx = dataclasses.replace(ctx, slot_close=cap["slot_close_all"]) qp = cap["q_pos"].to(q.device) B, S, h, dh = q.shape g, nb = k.shape[2], k_bar.shape[1] rep = h // g bi = torch.arange(B, device=q.device)[:, None] sc = dh ** -0.5 qq = q[bi, qp].float() # [B,P,h,dh] qs = (q_slot if q_slot is not None else q)[bi, qp].float() kb = k_bar.float().repeat_interleave(rep, dim=2) # [B,nb,h,dh] sl = torch.einsum("bphd,bchd->bphc", qs, kb) * sc pred = make_message_mask_pred(S, ctx, key_valid) kv = S + torch.arange(nb, device=q.device)[None, None] vis = pred(bi[:, :, None], None, qp[:, :, None], kv) # [B,P,nb] sl = sl.masked_fill(~vis[:, :, None], float("-inf")) W = int(ctx.raw_window or 0) or (int(qp.max()) + 1) j = qp[..., None] - torch.arange(W, device=q.device) # [B,P,W] kr = k[bi[..., None], j.clamp(min=0)].float().repeat_interleave(rep, dim=3) # [B,P,W,h,dh] rl = torch.einsum("bphd,bpwhd->bphw", qq, kr) * sc ok = pred(bi[:, :, None], None, qp[:, :, None], j.clamp(min=0)) & (j >= 0) rl = rl.masked_fill(~ok[:, :, None], float("-inf")) lse = torch.logsumexp(torch.cat([rl, sl], -1), -1, keepdim=True) cap.setdefault("mass", []).append(torch.exp(sl - lse).nan_to_num(0.0).sum(2)) # the request itself, for an agent A that scores its own notebook (`score_notes`): B's note query per head and the # log-total of B's own raw attention per head cap.setdefault("queries", []).append((qs, torch.logsumexp(rl, -1))) def read_target_loss(q, k, k_bar, ctx: MessageCtx, key_valid, *, q_slot=None) -> None: """Text multi-hop (2026-10-17): round r of a question's read should land on fact r of its chain. For this round's targets (`ctx.read_targets` rows with round == `ctx.read_round`) the share of the read's own softmax (raw window β€– the notes this query may see, logits qΒ·k and q_slotΒ·kΜ„ at 1/√dh, mean over heads) that falls on the fact β€” its raw tokens where they sit in the window, the notes of every page covering it otherwise β€” is turned into βˆ’log(share) and appended to `ctx.read_losses`. Differentiable; the E33d / E33e note terms are not included (as in `capture_note_mass`).""" rt = ctx.read_targets sel = (rt[..., 1] == int(ctx.read_round)) & (rt[..., 0] >= 0) if not bool(sel.any()): return bi, ti = sel.nonzero(as_tuple=True) qp, t0, t1 = rt[bi, ti, 0], rt[bi, ti, 2], rt[bi, ti, 3] B, S, h, dh = q.shape g, nb = k.shape[2], k_bar.shape[1] rep = h // g dev = q.device pred = make_message_mask_pred(S, ctx, key_valid) kv = S + torch.arange(nb, device=dev)[None] vis = pred(bi[:, None], None, qp[:, None], kv) # [N,nb] W = min(int(ctx.raw_window or 0) or S, S) j = qp[:, None] - torch.arange(W, device=dev)[None] # [N,W] raw positions, newest first jc = j.clamp(min=0) ok = pred(bi[:, None], None, qp[:, None], jc) & (j >= 0) raw_t = ok & (j >= t0[:, None]) & (j <= t1[:, None]) page = torch.arange(nb, device=dev) // max(1, int(ctx.notes_per_page)) st = ctx.page_starts.to(dev)[page.clamp(max=ctx.page_starts.numel() - 1)] note_t = vis & (st[None] <= t1[:, None]) & (st[None] + int(ctx.page_window) > t0[:, None]) if ctx.read_target == "note" and ctx.slot_pos is not None: # the notes whose latent read the span (its expected position within 2 tokens of it); the page if none does sp = ctx.slot_pos.to(dev)[bi] # [N,nb] near = vis & (sp >= t0[:, None] - 2) & (sp <= t1[:, None] + 2) note_t = torch.where(near.any(-1, keepdim=True), near, note_t) has = raw_t.any(-1) | note_t.any(-1) if not bool(has.any()): return bi, qp, vis, ok, jc, raw_t, note_t = bi[has], qp[has], vis[has], ok[has], jc[has], raw_t[has], note_t[has] N = bi.shape[0] sc = dh ** -0.5 with torch.autocast(device_type=dev.type, enabled=False): # fp32 throughout (autocast would make einsum bf16) qq = q[bi, qp].float().view(N, g, rep, dh) qs = (q_slot if q_slot is not None else q)[bi, qp].float().view(N, g, rep, dh) sl = torch.einsum("ngrd,ncgd->ngrc", qs, k_bar[bi].float()).reshape(N, h, nb) * sc rl = torch.einsum("ngrd,nwgd->ngrw", qq, k[bi[:, None], jc].float()).reshape(N, h, W) * sc neg = torch.finfo(torch.float32).min rl = rl.masked_fill(~ok[:, None], neg) sl = sl.masked_fill(~vis[:, None], neg) lse = torch.logsumexp(torch.cat([rl, sl], -1), -1) hit = torch.logsumexp(torch.cat([rl.masked_fill(~raw_t[:, None], neg), sl.masked_fill(~note_t[:, None], neg)], -1), -1) share = torch.exp(hit - lse).mean(-1) # [N] mean over heads ctx.read_losses.append(-torch.log(share.clamp(min=1e-6))) @torch.no_grad() def note_topk_threshold(q_slot: torch.Tensor, k_bar: torch.Tensor, ctx: MessageCtx, key_valid, *, k: int, chunk: int = 1024) -> torch.Tensor: """E33n: per (row, head, query) the k-th best score among the notes this query may see, [B,h,S] fp32. The score is the read's own slot logit, q_slotΒ·kΜ„ / √dh (the logit `attend_message` gives the notes). A query that sees at most k notes gets βˆ’inf (it keeps all of them). Computed in query chunks without gradient: the choice of the k notes carries no gradient, the logits of the kept notes keep theirs (LSA's native selection, arXiv 2610.42147, applied to compressed notes instead of raw keys). One KV head is shared by its query heads, so each query head ranks the notes by its own score.""" B, S, h, dh = q_slot.shape C, g = k_bar.shape[1], k_bar.shape[2] rep = h // g dev = q_slot.device sc = dh ** -0.5 pred = make_message_mask_pred(S, ctx, key_valid) bi = torch.arange(B, device=dev)[:, None, None] kv = S + torch.arange(C, device=dev)[None, None, :] kb = k_bar.float() kk = min(int(k), C) out = torch.full((B, h, S), float("-inf"), dtype=torch.float32, device=dev) for s0 in range(0, S, chunk): s1 = min(S, s0 + chunk) qi = torch.arange(s0, s1, device=dev)[None, :, None] vis = pred(bi, None, qi, kv) # [B,s,C] qq = q_slot[:, s0:s1].float().reshape(B, s1 - s0, g, rep, dh) lg = torch.einsum("bsgrd,bcgd->bgrsc", qq, kb).reshape(B, h, s1 - s0, C) * sc lg = lg.masked_fill(~vis[:, None], float("-inf")) t = lg.topk(kk, dim=-1).values[..., -1] # [B,h,s] many = (vis.sum(-1) > kk)[:, None] # [B,1,s] out[:, :, s0:s1] = torch.where(many, t, torch.full_like(t, float("-inf"))) return out def attend_message(q, k, v, k_bar, v_bar, *, ctx: MessageCtx, key_valid, backend, block_masks=None, q_slot=None, note_bias=None, opened=None, gist: bool = True): """Global read over raw keys β€– message slots with the E21 mask. Returns [B,S,h,dh]. `q_slot` (E31c "reader" slot keys): the query used against the slots instead of `q` (the un-rotated query, while `q` is RoPE'd for the raw keys). One softmax over both, done exactly by concatenating head dims: Q = [q, q_slot], raw K = [k, 0], slot K = [0, kΜ„], scale 1/√dh β€” so the raw logits are qΒ·k and the slot logits q_slotΒ·kΜ„. Values keep width dh. `note_bias` (E33d) = (slope [h], pos [B,S], slot_pos [B,C], unit, mode): adds `note_age_bias` to the slot logits only (flex `score_mod`, or a float mask on the SDPA path); raw logits are unchanged. E33e (mode "rank") = (slope [h], logcount [B,h,S,n_w], None, rep, "rank"): adds βˆ’slope[h] Β· logcount at each note's page (`note_rank_logcount`). E33p: `opened` (nn.exact_read.OpenTable) lets each query also read the raw tokens it opened beyond the window (its own per-query table; the kernel is exact, not sparse in compute: plan Β§0.2); `gist=False` masks the notes.""" B, S, h, dh = q.shape g = k.shape[2] if backend == "flash": raise NotImplementedError("message boundary needs flex or sdpa") if opened is not None or not gist: if note_bias is not None or q_slot is not None or int(getattr(ctx, "note_topk", 0) or 0) > 0: raise NotImplementedError("the E33p read is not combined with note_bias, reader slot queries or top-k") return _attend_open(q, k, v, k_bar, v_bar, ctx=ctx, key_valid=key_valid, backend=backend, opened=opened, gist=gist) if getattr(ctx, "capture", None) is not None: capture_note_mass(q, k, k_bar, ctx, key_valid, q_slot=q_slot) if getattr(ctx, "read_losses", None) is not None and ctx.read_targets is not None: read_target_loss(q, k, k_bar, ctx, key_valid, q_slot=q_slot) # E33n top-k note read: a note below its query's and head's k-th best score is cut from the softmax topk = int(getattr(ctx, "note_topk", 0) or 0) tau = None if topk > 0 and k_bar.shape[1] > topk and ctx.override == "real": if note_bias is not None: raise NotImplementedError("lm_read_topk is not combined with note_bias (E33d / E33e)") qs0 = q_slot if q_slot is not None else q # small slack below the k-th score: the kernel's bf16-input scores and these fp32 ones differ by ~1e-6 tau = note_topk_threshold(qs0, k_bar, ctx, key_valid, k=topk) - 1e-3 if backend != "flex": # SDPA (CPU / MPS tests): the keep mask on the slot columns, [B,h,S,C] rep_t = h // g lg = torch.einsum("bshd,bchd->bhsc", qs0.float(), k_bar.float().repeat_interleave(rep_t, dim=2)) * dh ** -0.5 topk_keep = lg >= tau[..., None] scale = None if q_slot is not None: q = torch.cat([q, q_slot.to(q.dtype)], dim=-1) k = torch.cat([k, torch.zeros_like(k)], dim=-1) k_bar = torch.cat([torch.zeros_like(k_bar), k_bar], dim=-1) scale = dh ** -0.5 K = torch.cat([k, k_bar.to(k.dtype)], dim=1) V = torch.cat([v, v_bar.to(v.dtype)], dim=1) qt, kt, vt = (t.transpose(1, 2) for t in (q, K, V)) if backend == "flex": from torch.nn.attention.flex_attention import create_block_mask memo_key = ("message", ctx.override, ctx.n_slots, getattr(ctx, "anchor_mode", "none"), ctx.raw_window) if block_masks is not None and memo_key in block_masks: bm = block_masks[memo_key] else: pred = make_message_mask_pred(S, ctx, key_valid) if S * (S + ctx.n_slots) > _CHUNKED_MASK_PAIRS and getattr(ctx, "anchor_mode", "none") == "none": bm = _band_block_mask(pred, B=B, Q_LEN=S, KV_LEN=S + ctx.n_slots, window=int(ctx.raw_window or 0), causal=True, device=q.device, extra_blocks=_message_extra_blocks(ctx, S)) elif S * (S + ctx.n_slots) > _CHUNKED_MASK_PAIRS: bm = _chunked_block_mask(pred, B=B, Q_LEN=S, KV_LEN=S + ctx.n_slots, device=q.device) else: bm = create_block_mask(pred, B=B, H=None, Q_LEN=S, KV_LEN=S + ctx.n_slots, device=q.device, _compile=torch.cuda.is_available()) if block_masks is not None: block_masks[memo_key] = bm qt, kt, vt = qt.contiguous(), kt.contiguous(), vt.contiguous() score_mod, kernel_options = None, None if note_bias is not None: slope, pos_t, spos, unit, mode = note_bias # One copy of the slopes per (row, head, query): flex accumulates a captured buffer's gradient # with atomic adds, and 9 shared addresses made the backward 2.3Γ— slower (our GPU server, 30M, 4k). sl = slope.to(torch.float32)[None, :, None].expand(B, h, S).contiguous() if mode == "rank": # One captured buffer, the bias per (row, head, reader, page) with the strength already in it (its # gradient reaches the strength through autograd). A page index depends on the key, so the buffer is # gathered as a full query Γ— key tile: with the default 128 Γ— 128 blocks that overflowed the 3090's # shared memory (148 KB of 99 KB), hence the smaller blocks. nbw = (-slope.to(torch.float32)[None, :, None, None] * pos_t.to(torch.float32)).contiguous() rep_i = int(unit) kernel_options = {"BLOCK_M": 64, "BLOCK_N": 64, "num_stages": 1, "bwd_BLOCK_M1": 32, "bwd_BLOCK_N1": 64, "bwd_BLOCK_M2": 64, "bwd_BLOCK_N2": 32} def score_mod(score, b, hh, q_idx, kv_idx): w = torch.div(torch.clamp(kv_idx - S, min=0), rep_i, rounding_mode="floor") return torch.where(kv_idx >= S, score + nbw[b, hh, q_idx, w], score) else: pos_f, spos_f = pos_t.to(torch.float32), spos.to(torch.float32) unit_f, log_f = float(unit), mode == "log" def score_mod(score, b, hh, q_idx, kv_idx): c = torch.clamp(kv_idx - S, min=0) age = torch.clamp(pos_f[b, q_idx] - spos_f[b, c], min=0.0) / unit_f f = torch.log1p(age) if log_f else age return torch.where(kv_idx >= S, score - sl[b, hh, q_idx] * f, score) elif tau is not None: tau_c = tau.contiguous() def score_mod(score, b, hh, q_idx, kv_idx): return torch.where((kv_idx >= S) & (score < tau_c[b, hh, q_idx]), -float("inf"), score) if kernel_options is not None and torch.cuda.is_available(): out = _get_flex()(qt, kt, vt, block_mask=bm, enable_gqa=(g != h), scale=scale, score_mod=score_mod, kernel_options=kernel_options) else: out = _get_flex()(qt, kt, vt, block_mask=bm, enable_gqa=(g != h), scale=scale, score_mod=score_mod) return out.transpose(1, 2) if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) mask = dense_message_mask(S, ctx, key_valid, q.device) if tau is not None: # E33n on SDPA: cut the notes below each query's and head's k-th score mask = mask.expand(B, h, S, mask.shape[-1]).clone() mask[..., S:] &= topk_keep if note_bias is not None: # E33d: float mask, per head, the bias on the slot columns only slope, pos_t, spos, unit, mode = note_bias fm = torch.zeros(mask.shape, dtype=torch.float32, device=q.device).masked_fill(~mask, float("-inf")) if mode == "rank": # E33e: the page count broadcast to the page's notes nb = -slope.to(torch.float32)[None, :, None, None] * pos_t.to(torch.float32).repeat_interleave(int(unit), dim=-1) else: nb = note_age_bias(pos_t, spos, slope, unit, mode) mask = torch.cat([fm[..., :S].expand(B, h, S, S), fm[..., S:] + nb], dim=-1).to(qt.dtype) dv = vt.shape[-1] if qt.shape[-1] != dv: # Reader mode (QK width 2Β·dh, V width dh). Some SDPA backends assume equal widths (MPS # returns the QK width; CUDA flash needs them equal), so pad V with zeros and slice: exact. vt = F.pad(vt, (0, qt.shape[-1] - dv)) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask, scale=scale)[..., :dv] return out.transpose(1, 2) def _attend_open(q, k, v, k_bar, v_bar, *, ctx: MessageCtx, key_valid, backend, opened, gist: bool): """E33p read: raw window β€– opened raw tokens β€– notes (gist) in one softmax. [B,S,h,dh] β†’ [B,S,h,dh].""" pass # nn.exact_read: in this file B, S, h, dh = q.shape g = k.shape[2] rw = int(ctx.raw_window or 0) K = torch.cat([k, k_bar.to(k.dtype)], dim=1) V = torch.cat([v, v_bar.to(v.dtype)], dim=1) qt, kt, vt = (t.transpose(1, 2) for t in (q, K, V)) if backend == "flex": term = open_term(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) if opened is not None else None pred = make_message_mask_pred(S, ctx, key_valid, opened=term, gist=gist) extra = [] if gist: e = _message_extra_blocks(ctx, S) if e is not None: extra.append(e) if opened is not None: extra.append(opened.extra_blocks()) bm = _band_block_mask(pred, B=B, Q_LEN=S, KV_LEN=S + ctx.n_slots, window=rw, causal=True, device=q.device, extra_blocks=torch.cat(extra, dim=-1) if extra else None) out = _get_flex()(qt.contiguous(), kt.contiguous(), vt.contiguous(), block_mask=bm, enable_gqa=(g != h)) return out.transpose(1, 2) if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) od = dense_open(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) if opened is not None else None mask = dense_message_mask(S, ctx, key_valid, q.device, opened=od, gist=gist) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask) return out.transpose(1, 2) def _attend_catalogue(q, k, v, sink_k, sink_v, *, ctx: MessageCtx, key_valid, backend, opened): """E33t catalogue read: one softmax over the raw window β€– the raw tokens this query opened β€– the learned empty slots. The notes do not appear (they only chose what opened). q [B,S,h,dh], k / v [B,S,g,dh], sink_k / sink_v [n,dh] or None, `opened` (nn.exact_read.OpenTable) or None β†’ [B,S,h,dh]. A slot is readable by every valid query.""" pass # nn.exact_read: in this file pass # nn.exact_read: in this file B, S, h, dh = q.shape g = k.shape[2] rw = int(ctx.raw_window or 0) n = 0 if sink_k is None else int(sink_k.shape[0]) if isinstance(opened, ChoiceList): # E33t stage C: the list read (evaluation at 128k–1M) if ctx.anchor is not None and bool(ctx.anchor.any()): raise NotImplementedError("the list read has no anchors") tag, _ = ctx.tags() ek = sink_k.to(k.dtype)[:, None, :].expand(n, g, dh) if n else None ev = sink_v.to(v.dtype)[:, None, :].expand(n, g, sink_v.shape[-1]) if n else None return attend_list(q, k, v, opened=opened, raw_window=rw, tag=tag, key_valid=key_valid, extra_k=ek, extra_v=ev) if n: K = torch.cat([k, sink_k.to(k.dtype)[None, :, None, :].expand(B, n, g, dh)], dim=1) V = torch.cat([v, sink_v.to(v.dtype)[None, :, None, :].expand(B, n, g, dh)], dim=1) else: K, V = k, v qt, kt, vt = (t.transpose(1, 2) for t in (q, K, V)) tag, _ = ctx.tags() if backend == "flex": term = open_term(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) if opened is not None else None base = make_message_mask_pred(S, ctx, key_valid, opened=term, gist=False) def pred(b, hh, qi, kv): return torch.where(kv < S, base(b, hh, qi, kv), (kv - S < n) & (tag[b, qi] >= 0)) nqb = -(-S // 128) extra = [] if n: lo_b, hi_b = S // 128, (S + n - 1) // 128 extra.append(torch.tensor([lo_b, hi_b], device=q.device).expand(B, nqb, 2)) if opened is not None: extra.append(opened.extra_blocks()) bm = _band_block_mask(pred, B=B, Q_LEN=S, KV_LEN=S + n, window=rw, causal=True, device=q.device, extra_blocks=torch.cat(extra, dim=-1) if extra else None) out = _get_flex()(qt.contiguous(), kt.contiguous(), vt.contiguous(), block_mask=bm, enable_gqa=(g != h)) return out.transpose(1, 2) if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) od = dense_open(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) if opened is not None else None raw = dense_message_mask(S, ctx, key_valid, q.device, opened=od, gist=False)[..., :S] mask = torch.cat([raw, (tag >= 0)[:, None, :, None].expand(B, raw.shape[1], S, n)], dim=-1) if n else raw out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask) return out.transpose(1, 2) def attend_list(q, k, v, *, opened, raw_window: int, tag: torch.Tensor, key_valid, extra_k=None, extra_v=None, ds: Optional[torch.Tensor] = None, n_sinks: int = 0, valid_query: bool = False, chunk: int = 256, q_offset: int = 0) -> torch.Tensor: """E33t stage C (plan Β§10.3), evaluation at 128k–1M: the exact read without the [B, S, G] table. Per chunk of queries, one softmax over the raw window β€– the raw tokens each query opened (`opened`, nn.exact_read.ChoiceList, or None) β€– the extra keys: the catalogue's learned empty slots (`extra_k` / `extra_v` [n, g, dh], readable by every query with tag β‰₯ 0) or LSA's sinks (the `n_sinks` first tokens of the query's document, `ds` [B, S] its start; those inside the window are read there, once). Window keys: j ≀ q, q βˆ’ j < raw_window, tag[j] == tag[q]; opened and sink keys: tag[j] == tag[q]; with `valid_query` (LSA) a query of tag < 0 reads nothing raw; key_valid[j] (or j == q) as in the table's masks. Same keys and weights as `_attend_catalogue` / `attend_lsa` with the table (tests: `test_list_read_matches_table`). q [B,S,h,dh], k / v [B,S,g,dh], tag [B,S] int β†’ [B,S,h,dh]; scale 1/√dh, fp32. `q_offset` (cached decoding, nn/incremental.py): q holds the queries [q_offset, q_offset + Q) of the row that k / v / tag cover (S = k.shape[1]); the output has Q rows.""" B, Q, h, dh = q.shape S = int(k.shape[1]) q0 = int(q_offset) g = k.shape[2] rep = h // g rw = int(raw_window) sc = dh ** -0.5 kvf = key_valid.bool() if key_valid is not None else None tag = tag.long() neg = float("-inf") out = torch.empty(B, Q, h, v.shape[-1], dtype=q.dtype, device=q.device) def take(x, pos): # x [B, S, ...] at pos [B, ch, P] β†’ [B, ch, P, ...] Bp, ch, P = pos.shape flat = pos.reshape(Bp, ch * P) if x.dim() == 2: return x.gather(1, flat).view(Bp, ch, P) idx = flat.view(Bp, ch * P, *([1] * (x.dim() - 2))).expand(Bp, ch * P, *x.shape[2:]) return x.gather(1, idx).view(Bp, ch, P, *x.shape[2:]) for s0 in range(q0, q0 + Q, chunk): s1 = min(q0 + Q, s0 + chunk) ch = s1 - s0 qp = torch.arange(s0, s1, device=q.device) qc = q[:, s0 - q0:s1 - q0].float().reshape(B, ch, g, rep, dh) tq = tag[:, s0:s1] logits, vals = [], [] # the raw window j0 = max(0, s0 - rw + 1) jw = torch.arange(j0, s1, device=q.device) d = qp[:, None] - jw[None, :] ok = ((d >= 0) & (d < rw))[None] & (tag[:, j0:s1][:, None, :] == tq[..., None]) if valid_query: ok = ok & (tq >= 0)[..., None] if kvf is not None: ok = ok & (kvf[:, j0:s1][:, None, :] | (d == 0)[None]) kw, vw = k[:, j0:s1].float(), v[:, j0:s1].float() lw = torch.einsum("bqgrd,bkgd->bqgrk", qc, kw) * sc logits.append(lw.masked_fill(~ok[:, :, None, None, :], neg)) vals.append(("shared", vw)) # the opened tokens if opened is not None: pos, ok = opened.opened(s0, s1, rw) if pos.shape[-1]: ok = ok & (take(tag, pos) == tq[..., None]) if valid_query: ok = ok & (tq >= 0)[..., None] if kvf is not None: ok = ok & take(kvf, pos) ko, vo = take(k, pos).float(), take(v, pos).float() # [B, ch, P, g, dh] lo = torch.einsum("bqgrd,bqpgd->bqgrp", qc, ko) * sc logits.append(lo.masked_fill(~ok[:, :, None, None, :], neg)) vals.append(("own", vo)) # learned empty slots (catalogue) if extra_k is not None and extra_k.shape[0]: le = torch.einsum("bqgrd,ngd->bqgrn", qc, extra_k.float()) * sc logits.append(le.masked_fill(~(tq >= 0)[:, :, None, None, None], neg)) vals.append(("slots", extra_v.float())) # LSA's sinks outside the window if n_sinks: sp = ds[:, s0:s1][..., None] + torch.arange(n_sinks, device=q.device) # [B, ch, n] ok = (sp <= qp[None, :, None]) & (qp[None, :, None] - sp >= rw) & (sp < S) spc = sp.clamp(max=S - 1) ok = ok & (take(tag, spc) == tq[..., None]) if valid_query: ok = ok & (tq >= 0)[..., None] if kvf is not None: ok = ok & take(kvf, spc) ks, vs = take(k, spc).float(), take(v, spc).float() ls = torch.einsum("bqgrd,bqpgd->bqgrp", qc, ks) * sc logits.append(ls.masked_fill(~ok[:, :, None, None, :], neg)) vals.append(("own", vs)) w = torch.nan_to_num(torch.softmax(torch.cat(logits, dim=-1), dim=-1), nan=0.0) o, a = 0.0, 0 for lg, (kind, val) in zip(logits, vals): n = lg.shape[-1] wi = w[..., a:a + n] a += n if kind == "shared": o = o + torch.einsum("bqgrk,bkgd->bqgrd", wi, val) elif kind == "own": o = o + torch.einsum("bqgrp,bqpgd->bqgrd", wi, val) else: o = o + torch.einsum("bqgrn,ngd->bqgrd", wi, val) out[:, s0 - q0:s1 - q0] = o.reshape(B, ch, h, -1).to(q.dtype) return out def attend_lsa(q, k, v, *, doc, key_valid, backend, opened, window: int, sink: torch.Tensor, ds: torch.Tensor, n_sinks: int): """LSA-native read on the global layer: sinks β€– raw window β€– the keys each query took (nn.lsa_buckets), one softmax over raw keys only, within the query's document. q [B,S,h,dh], k/v [B,S,g,dh], doc [B,S] (βˆ’1 = pad), `sink` [B,S] bool (the first tokens of each document), `ds` [B,S]: each token's document start.""" pass # nn.exact_read: in this file if isinstance(opened, ChoiceList): # E33t stage C: the list read (evaluation at 128k–1M) return attend_list(q, k, v, opened=opened, raw_window=int(window), tag=doc, key_valid=key_valid, ds=ds, n_sinks=int(n_sinks), valid_query=True) B, S, h, dh = q.shape g = k.shape[2] qt, kt, vt = (t.transpose(1, 2) for t in (q, k, v)) doc32 = doc.to(torch.int32) rw = int(window) if backend == "flex": term = open_term(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) if opened is not None else None sk = sink.to(torch.int32) def pred(b, hh, qi, j): same = (doc32[b, j] == doc32[b, qi]) & (doc32[b, qi] >= 0) ok = (j <= qi) & same keep = (qi - j < rw) | (sk[b, j] > 0) if term is not None: keep = keep | term(b, qi, j) ok = ok & keep if key_valid is not None: ok = ok & (key_valid[b, j] | (j == qi)) return ok nqb = -(-S // 128) first_q = torch.arange(nqb, device=q.device) * 128 sink_lo = ds[:, first_q] // 128 sink_hi = torch.clamp(ds[:, first_q] + max(n_sinks - 1, 0), max=S - 1) // 128 extra = [torch.stack([sink_lo, sink_hi], dim=-1)] if opened is not None: extra.append(opened.extra_blocks()) bm = _band_block_mask(pred, B=B, Q_LEN=S, KV_LEN=S, window=rw, causal=True, device=q.device, extra_blocks=torch.cat(extra, dim=-1)) out = _get_flex()(qt.contiguous(), kt.contiguous(), vt.contiguous(), block_mask=bm, enable_gqa=(g != h)) return out.transpose(1, 2) if g != h: rep = h // g kt = kt.repeat_interleave(rep, dim=1) vt = vt.repeat_interleave(rep, dim=1) qi = torch.arange(S, device=q.device)[:, None] j = torch.arange(S, device=q.device)[None, :] same = (doc[:, :, None] == doc[:, None, :]) & (doc[:, :, None] >= 0) keep = (qi - j < rw)[None] | sink[:, None, :] if opened is not None: keep = keep | dense_open(opened.T, opened.index.codes, cap=opened.cap, raw_window=rw) mask = (j <= qi)[None] & same & keep if key_valid is not None: mask = mask & (key_valid.bool()[:, None, :] | torch.eye(S, dtype=torch.bool, device=q.device)[None]) out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask[:, None]) return out.transpose(1, 2) # -------------------------------------------------------------------------------------- # Input: tiny factorized embedding + hashed n-gram tables # -------------------------------------------------------------------------------------- _HASH_PRIMES = (0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1) def hashed_ngram_ids( ids: torch.Tensor, order: int, buckets: int, doc_ids: Optional[torch.Tensor] = None ) -> torch.Tensor: """Deterministic bucket id of the n-gram ending at each position. Positions whose n-gram would cross the sequence start (or a document boundary when `doc_ids` is given) use a sentinel for the out-of-range part, so the first token of a document always hashes the same way regardless of what precedes it. """ B, S = ids.shape sentinel = torch.full_like(ids, -1) acc = torch.zeros_like(ids, dtype=torch.int64) for j in range(order): shifted = ids[:, : S - j] if j == 0 else torch.cat([sentinel[:, :j], ids[:, : S - j]], dim=1) if doc_ids is not None and j > 0: same = torch.cat( [torch.zeros(B, j, dtype=torch.bool, device=ids.device), doc_ids[:, j:] == doc_ids[:, : S - j]], dim=1, ) shifted = torch.where(same, shifted, sentinel) acc = acc ^ ((shifted.to(torch.int64) + 2) * _HASH_PRIMES[j % len(_HASH_PRIMES)]) acc = acc & 0x7FFFFFFFFFFFFFFF return acc % buckets def note_age_init(spec: str, h: int) -> torch.Tensor: """E33g: per-head starting strengths of the note-order term. "a" = every head; "a,b,…" with fewer values than heads = the LAST heads (the first ones stay at 0), so one pattern keeps the same order heads at every size.""" if not str(spec or "").strip(): return torch.zeros(h) vals = [float(x) for x in str(spec).split(",")] if len(vals) == 1: vals = vals * h if len(vals) > h: raise ValueError(f"lm_note_age_init has {len(vals)} values for {h} query heads") vals = [0.0] * (h - len(vals)) + vals return torch.tensor(vals, dtype=torch.float32) def note_count(qc: torch.Tensor, k_bar: torch.Tensor, k_raw: torch.Tensor, ctx: "MessageCtx", *, scale: float, window: int, stride: int, a: torch.Tensor, b: torch.Tensor, chunk: int = 512) -> torch.Tensor: """E33h: a summing read β€” how many things match the count query, [B,S,nc] fp32 (with gradient). A softmax read returns an average, so it cannot tell three matching visits from five. Here each count head h adds up Οƒ(a_h Β· qΒ·k Β· scale + b_h) over everything the reader at t may see, each token of the document once: - notes of closed pages of the same document, but only the notes whose read position lies in the first `stride` tokens of their page (pages are `window` tokens long and overlap by window βˆ’ stride; a token in the overlap belongs to the later page, so no event is counted twice); - the raw keys k_raw of the tokens no closed page owns yet: after (newest close βˆ’ (window βˆ’ stride)), up to t. `k_bar` [B,C,g,dh] and `k_raw` [B,S,g,dh] use their first key head; `qc` [B,S,nc,dh].""" B, S, nc, dh = qc.shape sd, sc, sp = ctx.slot_doc, ctx.slot_close, ctx.slot_pos ok = (sd >= 0) & (sc >= 0) own = ok & ((sp - (sc - window + 1)) < stride) # [B,C] kb, kr = k_bar[:, :, 0].float(), k_raw[:, :, 0].float() aa, bb = a.float()[None, :, None, None], b.float()[None, :, None, None] out = [] for s0 in range(0, S, chunk): s1 = min(S, s0 + chunk) t = torch.arange(s0, s1, device=qc.device) doc_t = ctx.doc[:, s0:s1] q = qc[:, s0:s1].float() seen = ok[:, None, :] & (sd[:, None, :] == doc_t[:, :, None]) & (sc[:, None, :] <= t[None, :, None]) # [B,s,C] last = torch.where(seen, sc[:, None, :], torch.full_like(sc[:, None, :], -(10 ** 9))).amax(-1) # [B,s] ln = torch.einsum("bshd,bcd->bhsc", q, kb) * scale cnt = (torch.sigmoid(aa * ln + bb) * (seen & own[:, None, :])[:, None]).sum(-1) # [B,nc,s] r0 = max(0, s0 - window) r = torch.arange(r0, s1, device=qc.device) lr = torch.einsum("bshd,brd->bhsr", q, kr[:, r0:s1]) * scale rvis = ((r[None, None, :] <= t[None, :, None]) & (r[None, None, :] > t[None, :, None] - window) & (ctx.doc[:, None, r0:s1] == doc_t[:, :, None]) & (doc_t[:, :, None] >= 0) & (r[None, None, :] > (last - (window - stride))[:, :, None])) cnt = cnt + (torch.sigmoid(aa * lr + bb) * rvis[:, None]).sum(-1) out.append(cnt) return torch.cat(out, dim=-1).transpose(1, 2) class NoteCounter(nn.Module): """E33h: count heads beside the global read. Own query from the layer input; keys = the notes' keys and the layer's raw keys; the summed gates (note_count) are coded as a soft one-hot over 0..count_max plus log(1 + n) and added to the read's output through a zero-initialised projection, so at step 0 the model is unchanged.""" def __init__(self, cfg, d: int, dh: int): super().__init__() self.nc, self.dh = int(cfg.lm_count_heads), dh self.kmax = int(getattr(cfg, "lm_count_max", 10)) self.window, self.stride = int(cfg.lm_window), int(cfg.lm_stride) self.wq = nn.Linear(d, self.nc * dh, bias=False) self.qn = nn.RMSNorm(dh) # gate Οƒ(aΒ·l + b): with unit-RMS queries and keys l β‰ˆ ±√dh; a = 2, b = βˆ’10 keeps unrelated keys near 0 # (Οƒ(βˆ’10) β‰ˆ 5e-5, so ~1,000 visible keys add β‰ˆ 0.05) while a strong match (l β‰ˆ 8) counts β‰ˆ 1 self.log_a = nn.Parameter(torch.full((self.nc,), math.log(2.0))) self.b = nn.Parameter(torch.full((self.nc,), -10.0)) self.out = nn.Linear(self.nc * (self.kmax + 2), d, bias=False) nn.init.zeros_(self.out.weight) self.register_buffer("levels", torch.arange(self.kmax + 1, dtype=torch.float32), persistent=False) self.last_count = None def forward(self, x, k_bar, k_raw, ctx) -> torch.Tensor: B, S, _ = x.shape qc = self.qn(self.wq(x).view(B, S, self.nc, self.dh)) n = note_count(qc, k_bar, k_raw, ctx, scale=self.dh ** -0.5, window=self.window, stride=self.stride, a=self.log_a.exp(), b=self.b) # [B,S,nc] self.last_count = n.detach() self.last_n = n if self.training else None # E33k: the count loss reads the summed gates with gradient rbf = torch.exp(-2.0 * (n[..., None] - self.levels) ** 2) # [B,S,nc,K+1], width 0.5 feats = torch.cat([rbf, torch.log1p(n)[..., None]], dim=-1).reshape(B, S, -1) return self.out(feats.to(self.out.weight.dtype)) class TiedFactorizedHead(nn.Module): """Output layer that shares the input token table (2026-11-14, for the Tiny-ML leaderboard's 150M cap). logits = (h Β· Pα΅€) Β· Eα΅€ with E the input table [V, e] (`embed.tok`) and P a projection [e, H]: the table is stored and counted once, and the head adds HΒ·e parameters instead of HΒ·V (at width 896 and e = 384 with the SmolLM2 vocabulary: 0.34M instead of 44M). The model's own loss paths call `project` and use `table` ([B,S,e] against [V,e]); `weight` is the effective [V, H] matrix EΒ·P for code that multiplies hidden states directly (evaluation, cached decoding), so `F.linear(h, lm_head.weight)` gives the same logits everywhere. E is held by reference, not registered a second time, so the state dict carries it once (as `embed.tok.weight`).""" def __init__(self, tok: nn.Embedding, hidden: int): super().__init__() self.proj = nn.Linear(hidden, tok.weight.shape[1], bias=False) object.__setattr__(self, "_tok", tok) @property def table(self) -> torch.Tensor: return self._tok.weight @property def weight(self) -> torch.Tensor: return self._tok.weight @ self.proj.weight def project(self, h: torch.Tensor) -> torch.Tensor: return self.proj(h) def forward(self, h: torch.Tensor) -> torch.Tensor: return F.linear(self.proj(h), self._tok.weight) class TinyHashedEmbedding(nn.Module): """token table [V,e] + Ξ£ n-gram tables [buckets,e] β†’ MLP up-projection to d β†’ RMSNorm.""" def __init__(self, cfg: PerceiverARConfig): super().__init__() e, d = cfg.token_embedding_dim, cfg.hidden_size self.orders = cfg.ngram_orders self.buckets = cfg.ngram_buckets self.tok = nn.Embedding(cfg.vocab_size, e) self.ngram = nn.ModuleList([nn.Embedding(cfg.ngram_buckets, e) for _ in self.orders]) self.up0 = nn.Linear(e, d, bias=False) self.up1 = nn.Linear(e, d, bias=False) self.up2 = nn.Linear(d, d, bias=False) self.norm = nn.RMSNorm(d) def forward(self, ids: torch.Tensor, doc_ids: Optional[torch.Tensor] = None) -> torch.Tensor: x = self.tok(ids) for order, table in zip(self.orders, self.ngram): x = x + table(hashed_ngram_ids(ids, order, self.buckets, doc_ids)) h = self.up0(x) + self.up2(F.silu(self.up1(x))) return self.norm(h) # -------------------------------------------------------------------------------------- # Blocks # -------------------------------------------------------------------------------------- def rope_cos_sin(positions: torch.Tensor, dim: int, theta: float, dtype) -> tuple[torch.Tensor, torch.Tensor]: """positions [B,S] β†’ cos, sin [B,S,1,dim] (rotate-half convention).""" inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=positions.device, dtype=torch.float32) / dim)) freqs = positions.to(torch.float32)[..., None] * inv # [B,S,dim/2] emb = torch.cat([freqs, freqs], dim=-1) return emb.cos().to(dtype)[:, :, None, :], emb.sin().to(dtype)[:, :, None, :] def rope_cos_sin_mixed(pos_hi: torch.Tensor, pos_lo: torch.Tensor, dim: int, theta: float, dtype): """Slot-key RoPE with two positions: the high-frequency half of the rotation pairs at `pos_hi`, the low-frequency half at `pos_lo` (the "mixed" slot position: content at the QUERY boundary, order at a scaled distance). Same layout as `rope_cos_sin`.""" half = dim // 2 inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=pos_hi.device, dtype=torch.float32) / dim)) split = half // 2 f_hi = pos_hi.to(torch.float32)[..., None] * inv[:split] f_lo = pos_lo.to(torch.float32)[..., None] * inv[split:] freqs = torch.cat([f_hi, f_lo], dim=-1) emb = torch.cat([freqs, freqs], dim=-1) return emb.cos().to(dtype)[:, :, None, :], emb.sin().to(dtype)[:, :, None, :] def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: half = x.shape[-1] // 2 x1, x2 = x[..., :half], x[..., half:] rot = torch.cat([-x2, x1], dim=-1) return x * cos + rot * sin class Attention(nn.Module): def __init__(self, cfg: PerceiverARConfig, layer_idx: int, pattern: str, window: int): super().__init__() d, h, g, dh = cfg.hidden_size, cfg.num_attention_heads, cfg.num_kv_heads, cfg.head_dim self.h, self.g, self.dh = h, g, dh self.pattern, self.window = pattern, window self.layer_idx = layer_idx self.backend = cfg.attn_backend self.causal = True self.sink = bool(getattr(cfg, "swa_sink", False)) and pattern == "swa" self.wq = nn.Linear(d, h * dh, bias=False) self.wk = nn.Linear(d, g * dh, bias=False) self.wv = nn.Linear(d, g * dh, bias=False) self.wo = nn.Linear(h * dh, d, bias=False) self.q_norm = nn.RMSNorm(dh) self.k_norm = nn.RMSNorm(dh) self.use_rope = True # SSMax-style length-aware query scale on the unbounded read: q *= s * log(n_visible). # s is learnable, initialised so the factor is exactly 1 at n = global_scale_ref. self.logit_scale = None if pattern == "full" and getattr(cfg, "global_logit_scale", "none") == "log": self.logit_scale = nn.Parameter(torch.tensor(1.0 / math.log(cfg.global_scale_ref))) self.value_embed = None if layer_idx in cfg.value_embed_layers: self.value_embed = nn.Embedding(cfg.vocab_size, cfg.value_embed_dim) self.value_proj = nn.Linear(cfg.value_embed_dim, g * dh, bias=False) self.value_lambda = nn.Parameter(torch.tensor(0.5)) # Exclusive write: E21 block-mean or E30 overlapping Perceiver banks. write = str(getattr(cfg, "message_write", "block_mean") or "block_mean") if getattr(cfg, "message_enabled", False) and pattern == "full": if write == "sw_perceiver": self.compressor = SlidingWindowPerceiverCompressor(cfg) elif write == "latent_memory": self.compressor = None # E31: slots come from the model-level writer (ctx.slots) else: self.compressor = KVCompressor(cfg) else: self.compressor = None self.prefix_ae = bool(getattr(cfg, "message_prefix_ae", False)) self.prefix_ae_stopgrad = bool(getattr(cfg, "message_prefix_ae_stopgrad_answer", True)) self._last_k_bar = None self._last_v_bar = None # E33d: one signed slope per query head for the page distance of each note (outside the key). # Zero at the start, so the read is exactly the E31c/E33 read until training moves it. self.note_age_slope = None self.note_age_mode = str(getattr(cfg, "lm_note_age", "none") or "none") if (self.note_age_mode != "none" and pattern == "full" and write == "latent_memory" and getattr(cfg, "message_enabled", False)): self.note_age_slope = nn.Parameter(note_age_init(getattr(cfg, "lm_note_age_init", ""), h), requires_grad=bool(getattr(cfg, "lm_note_age_learn", True))) self.note_age_unit = float(getattr(cfg, "lm_note_age_unit", 0) or cfg.lm_stride) # E33e (rank): the same per-head strength, in front of the count of newer matching notes self.note_rank_rep = int(cfg.lm_latents) * int(cfg.lm_reader_tokens) self.note_rank_margin = float(getattr(cfg, "lm_note_rank_margin", 1.0)) self.note_rank_sharp = float(getattr(cfg, "lm_note_rank_sharp", 2.0)) # E33g2: "content" = the match is judged by the heads with strength 0 (the content heads), for every head self.note_rank_gate = str(getattr(cfg, "lm_note_rank_gate", "own") or "own") # E33i: a per-position switch on the order term (initialised in the model, after post_init) self.note_order_gate = (nn.Linear(cfg.hidden_size, 1) if bool(getattr(cfg, "lm_note_order_gate", False)) and self.note_age_mode == "rank" else None) # E33p: LSA's released flat read on the global layer (the LSA-native arm; nn/lsa_buckets.py) self.lsa = None self.lsa_off = False # eval switch (`PerceiverARLM.open_override("off")`): sinks + window only self.open_impl = "table" # E33t stage C eval switch (`PerceiverARLM.open_impl`): "list" = no [B, S, G] table if pattern == "full" and str(getattr(cfg, "par_global_read", "dense") or "dense") == "lsa": self.lsa = dict(window=int(cfg.lsa_window), sinks=int(cfg.lsa_sinks), block=int(cfg.lsa_block), per_block=int(cfg.lsa_block) // int(cfg.lsa_bucket), pool=int(cfg.lsa_pool), cap=int(cfg.lsa_bucket_cap), top_k=int(cfg.lsa_top_k), width=int(cfg.lsa_width)) # E37: the concept memory read on the global layer (nn/concept_memory.py): encoder β†’ reasoner β†’ decoder read self.concept = None self.concept_reasoner = None self.concept_off = False # eval switch: sinks + window only (no opened tokens, no summaries) self.concept_stats = None # last forward's read statistics when armed (dict), for probes if pattern == "full" and str(getattr(cfg, "par_global_read", "dense") or "dense") == "concept": self.concept = dict(block=int(cfg.concept_block), per_block=int(cfg.concept_per_block), iters=int(cfg.concept_iters), tau=float(cfg.concept_tau), sinks=int(cfg.concept_sinks), top_k=int(cfg.concept_top_k), width=int(cfg.concept_width), summaries=bool(cfg.concept_summaries), variance=bool(cfg.concept_variance), sum_len=int(getattr(cfg, "concept_sum_len", 0) or 0)) if int(getattr(cfg, "concept_reasoner_layers", 0) or 0) > 0: pass # nn.concept_memory: in this file self.concept_reasoner = ConceptReasoner( cfg.hidden_size, g * dh, dim=int(cfg.concept_reasoner_dim), layers=int(cfg.concept_reasoner_layers), heads=int(cfg.concept_reasoner_heads), loops=int(cfg.concept_reasoner_loops)) self.flow = None # E33p instrumentation (nn/flow_stats.FlowRecorder), set on the reading layer when armed # E33t: the catalogue read's learned empty slots (keys through k_norm, values from zero) and the index loss's # temperature, on the reading layer only self.sink_k = self.sink_v = self.index_log_tau = None if (pattern == "full" and write == "latent_memory" and getattr(cfg, "message_enabled", False) and str(getattr(cfg, "lm_note_read", "gist") or "gist") == "index"): n_s = int(getattr(cfg, "lm_sinks", 0) or 0) if n_s > 0: self.sink_k = nn.Parameter(torch.randn(n_s, dh) * float(getattr(cfg, "init_std", 0.02))) self.sink_v = nn.Parameter(torch.zeros(n_s, dh)) if float(getattr(cfg, "lm_index_loss", 0.0) or 0.0) > 0: self.index_log_tau = nn.Parameter(torch.tensor(math.log(10.0))) self.index_queries = int(getattr(cfg, "lm_index_queries", 256) or 256) self.index_negatives = int(getattr(cfg, "lm_index_negatives", 32) or 0) # E33h: count heads (a summing read) on the latent-memory global read self.note_counter = None if (int(getattr(cfg, "lm_count_heads", 0) or 0) > 0 and pattern == "full" and write == "latent_memory" and getattr(cfg, "message_enabled", False)): self.note_counter = NoteCounter(cfg, cfg.hidden_size, self.dh) def kv_raw(self, x: torch.Tensor, ids: Optional[torch.Tensor] = None) -> tuple[torch.Tensor, torch.Tensor]: """(k before k_norm, v incl. the value-embedding term) β€” the pooling inputs of the compressor.""" B, S, _ = x.shape k_raw = self.wk(x).view(B, S, self.g, self.dh) v = self.wv(x).view(B, S, self.g, self.dh) if self.value_embed is not None and ids is not None: ve = self.value_proj(self.value_embed(ids)).view(B, S, self.g, self.dh) v = v + self.value_lambda * ve return k_raw, v def kv(self, x: torch.Tensor, ids: Optional[torch.Tensor] = None) -> tuple[torch.Tensor, torch.Tensor]: k_raw, v = self.kv_raw(x, ids) return self.k_norm(k_raw), v def message_slots(self, x, k_raw, v, ctx: MessageCtx, key_valid, cfg_rope_theta: float, *, rope: bool = True): """(kΜ„, vΜ„) [B,nb,g,dh] for this forward: external slots (receiver-only forward) or the compressor over the block input, RoPE'd at each slot's position unless `rope=False` (in-place path applies token-position RoPE after scatter).""" if ctx.external is not None: return ctx.external if ctx.slots is not None: return ctx.slots valid = key_valid if ctx.pool_valid is not None: pv = ctx.pool_valid.bool() valid = pv if valid is None else (valid.bool() & pv) if isinstance(self.compressor, SlidingWindowPerceiverCompressor) and ctx.window_valid is not None: k_bar, v_bar = self.compressor(x, k_raw, v, self.k_norm, valid, window_valid=ctx.window_valid) else: k_bar, v_bar = self.compressor(x, k_raw, v, self.k_norm, valid) self._last_k_bar = k_bar self._last_v_bar = v_bar if self.prefix_ae and self.prefix_ae_stopgrad: k_bar, v_bar = k_bar.detach(), v_bar.detach() if rope and self.use_rope: if ctx.slot_pos_lo is not None: cos_s, sin_s = rope_cos_sin_mixed(ctx.slot_pos, ctx.slot_pos_lo, self.dh, cfg_rope_theta, k_bar.dtype) else: cos_s, sin_s = rope_cos_sin(ctx.slot_pos, self.dh, cfg_rope_theta, k_bar.dtype) k_bar = apply_rope(k_bar, cos_s, sin_s) if rope: self._last_slots = (k_bar, v_bar) # E33 read rounds reuse these (frozen memory) return k_bar, v_bar def _scale_q(self, q, pos): if self.logit_scale is not None: if pos is None: raise RuntimeError("global_logit_scale='log' needs per-token positions") n_vis = (pos + 1).to(q.dtype) q = q * (self.logit_scale * torch.log(n_vis))[:, :, None, None] return q def _extra_exclusive_attends(self, x, out, *, extra, cos, sin, pos, attend_fn, rewrite_kv=None): """Re-read exclusive slot K/V with queries updated by the previous hop. `attend_fn(q) -> [B,S,h,dh]`. Extra=0 is a no-op (byte-identical first hop). Default: K/V stay the snapshot from the first hop β€” not recomputed, not raw prefix. When `rewrite_kv` is set (`message_update_slot_kv`), it is called with the post-attend residual `h` before each extra hop and must return a new `attend_fn` bound to rewritten exclusive slot K/V. Still not full prefix. """ extra = int(extra or 0) if extra <= 0: return out B, S, _ = x.shape h = x for _ in range(extra): h = h + out q = self.q_norm(self.wq(h).view(B, S, self.h, self.dh)) if self.use_rope: q = apply_rope(q, cos, sin) q = self._scale_q(q, pos) if rewrite_kv is not None: attend_fn = rewrite_kv(h) o = attend_fn(q) out = self.wo(o.reshape(B, S, self.h * self.dh)) return out def forward(self, x, *, ids, cos, sin, key_valid, doc_ids, cu_seqlens, block_masks=None, sink_pos=None, pos=None, message: Optional[MessageCtx] = None, rope_theta: float = 500000.0): B, S, _ = x.shape q = self.q_norm(self.wq(x).view(B, S, self.h, self.dh)) k_raw, v = self.kv_raw(x, ids) k_un = self.k_norm(k_raw) extra = int(getattr(message, "extra_slot_attends", 0) or 0) if message is not None else 0 update_kv = bool(getattr(message, "update_slot_kv", False)) if message is not None else False use_inplace = ( message is not None and self.compressor is not None and bool(getattr(message, "inplace", False)) and message.override in ("real", "swapped") and message.external is None ) if use_inplace: raw_kv = bool(getattr(message, "inplace_raw_kv", False)) if raw_kv: k_mix, v_mix, replace = mix_inplace_kv(k_un, v, k_un, v, message) else: k_bar, v_bar = self.message_slots(x, k_raw, v, message, key_valid, rope_theta, rope=False) if message.override == "swapped": k_bar, v_bar = k_bar.roll(1, dims=0), v_bar.roll(1, dims=0) k_mix, v_mix, replace = mix_inplace_kv(k_un, v, k_bar, v_bar, message) k_tok, v_tok = k_un, v # un-RoPE'd first-hop token K/V (non-slot positions stay these) if self.use_rope: q = apply_rope(q, cos, sin) k_mix = apply_rope(k_mix, cos, sin) q = self._scale_q(q, pos) o = attend_inplace( q, k_mix, v_mix, ctx=message, replace=replace, key_valid=key_valid, backend=self.backend, block_masks=block_masks, ) out = self.wo(o.reshape(B, S, self.h * self.dh)) def _rewrite_inplace(h): k_raw2, v2 = self.kv_raw(h, ids) k_un2 = self.k_norm(k_raw2) if raw_kv: k_bar2, v_bar2 = k_un2, v2 else: k_bar2, v_bar2 = self.message_slots( h, k_raw2, v2, message, key_valid, rope_theta, rope=False, ) if message.override == "swapped": k_bar2, v_bar2 = k_bar2.roll(1, dims=0), v_bar2.roll(1, dims=0) k_mix2, v_mix2, _ = mix_inplace_kv(k_tok, v_tok, k_bar2, v_bar2, message) if self.use_rope: k_mix2 = apply_rope(k_mix2, cos, sin) return lambda qq: attend_inplace( qq, k_mix2, v_mix2, ctx=message, replace=replace, key_valid=key_valid, backend=self.backend, block_masks=block_masks, ) out = self._extra_exclusive_attends( x, out, extra=extra, cos=cos, sin=sin, pos=pos, attend_fn=lambda qq: attend_inplace( qq, k_mix, v_mix, ctx=message, replace=replace, key_valid=key_valid, backend=self.backend, block_masks=block_masks, ), rewrite_kv=_rewrite_inplace if update_kv else None, ) if raw_kv: out = out + 0.0 * self.compressor.participation().to(out.dtype) return out k = k_un q_un = q if self.use_rope: q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) q = self._scale_q(q, pos) if message is not None and (self.compressor is not None or message.slots is not None): k_bar, v_bar = self.message_slots(x, k_raw, v, message, key_valid, rope_theta) if message.override == "swapped": k_bar, v_bar = k_bar.roll(1, dims=0), v_bar.roll(1, dims=0) opened, gist = None, True ni = getattr(message, "index", None) catalogue = ni is not None and getattr(ni, "read", "gist") == "index" # E33t sink_keys = self.k_norm(self.sink_k).to(k.dtype) if (catalogue and self.sink_k is not None) else None if ni is not None: # E33p: tied note keys, and the raw tokens each query opens pass # nn.exact_read: in this file kappa = tied_note_keys(ni.assign, k, ni.page_tok) if message.override == "swapped": kappa = kappa.roll(1, dims=0) # the writer's own key is unused: a zero term keeps its parameters in the graph (DDP) k_bar = kappa.to(k.dtype) + 0.0 * k_bar.sum() ev = getattr(message, "open_eval", "on") gist = ev != "gist_off" and not catalogue if ni.mode != "none" and message.override == "real" and ev != "off": excl = bool(getattr(ni, "new_per_pass", False)) and ev != "reuse" pkey = (page_keys(k, ni.page_tok, ni.pick) if getattr(ni, "levels", 1) == 2 and ni.pick is not None else None) impl = self.open_impl if impl == "list" and (not catalogue or excl or self.training): raise NotImplementedError("the list read is for evaluating catalogue arms without pass " "exclusion (E33t stage C)") opened = note_open_table(q, k_bar, ni, doc=message.doc, slot_close=message.slot_close, slot_doc=message.slot_doc, raw_window=int(message.raw_window or 0), exclude=message.open_seen if excl else None, page_key=pkey, impl=impl) if excl: # E33t: a later pass looks somewhere new seen = opened.T < opened.cap message.open_seen = seen if message.open_seen is None else (message.open_seen | seen) if (catalogue and self.training and self.index_log_tau is not None and message.index_losses is not None): pass # nn.exact_read: in this file il, st = index_loss(q, k, sink_keys, k_bar, opened, doc=message.doc, raw_window=int(message.raw_window or 0), n_queries=self.index_queries, n_neg=self.index_negatives, log_tau=self.index_log_tau, seen=message.open_seen if excl else None) message.index_losses.append(il) if self.flow is not None: self.flow.index_stats(st, self.index_log_tau) if self.flow is not None and message.read_rule == "closed": self.flow.reading_open(self, q=q, k=k, v=v, k_bar=k_bar, v_bar=v_bar, ctx=message, key_valid=key_valid, opened=opened, gist=gist, index=ni, sink_k=sink_keys if catalogue else None) # E31c "reader" slot keys: met by the un-rotated query (exact; see attend_message) q_slot = self._scale_q(q_un, pos) if (getattr(message, "slot_nope", False) and self.use_rope) else None note_bias = None if self.note_age_slope is not None and message.slot_pos is not None and pos is not None: if self.note_age_mode == "rank": if message.override not in ("none", "raw"): gh = None if getattr(self, "note_rank_gate", "own") == "content": gh = (self.note_age_slope.detach() == 0).nonzero().flatten().tolist() or None lc = note_rank_logcount(q_slot if q_slot is not None else q, k_bar, message, scale=self.dh ** -0.5, rep=self.note_rank_rep, margin=self.note_rank_margin, sharp=self.note_rank_sharp, gate_heads=gh) if getattr(self, "note_order_gate", None) is not None: # E33i: [B,S,1] β†’ [B,1,S,1]; the gradient reaches the switch through the bias buffer gam = torch.sigmoid(self.note_order_gate(x).float()).transpose(1, 2)[..., None] lc = lc * gam note_bias = (self.note_age_slope, lc, None, self.note_rank_rep, "rank") else: note_bias = (self.note_age_slope, pos, message.slot_pos, self.note_age_unit, self.note_age_mode) if catalogue: # E33t: raw window β€– opened tokens β€– empty slots; the notes only chose o = _attend_catalogue(q, k, v, sink_keys, self.sink_v.to(v.dtype) if self.sink_v is not None else None, ctx=message, key_valid=key_valid, backend=self.backend, opened=opened) else: o = attend_message(q, k, v, k_bar, v_bar, ctx=message, key_valid=key_valid, backend=self.backend, block_masks=block_masks, q_slot=q_slot, note_bias=note_bias, opened=opened, gist=gist) out = self.wo(o.reshape(B, S, self.h * self.dh)) if catalogue: # the writer's note values are not read: keep them in the graph (DDP) out = out + 0.0 * v_bar.sum().to(out.dtype) if self.index_log_tau is not None: out = out + 0.0 * self.index_log_tau.to(out.dtype) if self.note_age_slope is not None and note_bias is None: out = out + 0.0 * self.note_age_slope.sum().to(out.dtype) if self.note_counter is not None: if message.override not in ("none", "raw") and message.slot_close is not None: out = out + self.note_counter(x, k_bar, k_un, message).to(out.dtype) else: out = out + 0.0 * sum(p.sum() for p in self.note_counter.parameters()).to(out.dtype) def _rewrite_concat(h): k_raw2, v2 = self.kv_raw(h, ids) k_bar2, v_bar2 = self.message_slots(h, k_raw2, v2, message, key_valid, rope_theta) if message.override == "swapped": k_bar2, v_bar2 = k_bar2.roll(1, dims=0), v_bar2.roll(1, dims=0) return lambda qq: attend_message( qq, k, v, k_bar2, v_bar2, ctx=message, key_valid=key_valid, backend=self.backend, block_masks=block_masks, ) return self._extra_exclusive_attends( x, out, extra=extra, cos=cos, sin=sin, pos=pos, attend_fn=lambda qq: attend_message( qq, k, v, k_bar, v_bar, ctx=message, key_valid=key_valid, backend=self.backend, block_masks=block_masks, ), rewrite_kv=_rewrite_concat if update_kv else None, ) if self.lsa is not None: o = self._lsa_read(q, k, v, doc_ids=doc_ids, key_valid=key_valid) elif self.concept is not None: o = self._concept_read(q, k, v, x, doc_ids=doc_ids, key_valid=key_valid) else: if self.flow is not None and self.pattern == "full": self.flow.reading_dense(self, q=q, k=k, v=v, doc_ids=doc_ids, key_valid=key_valid) o = attend( q, k, v, pattern=self.pattern, window=self.window, key_valid=key_valid, doc_ids=doc_ids, backend=self.backend, causal=self.causal, cu_seqlens=cu_seqlens, block_masks=block_masks, sink=self.sink, sink_pos=sink_pos, ) o = self.wo(o.reshape(B, S, self.h * self.dh)) if self.compressor is not None: o = o + 0.0 * self.compressor.participation().to(o.dtype) if self.note_age_slope is not None: o = o + 0.0 * self.note_age_slope.sum().to(o.dtype) return o def _lsa_read(self, q, k, v, *, doc_ids, key_valid): """E33p LSA-native arm: buckets of this call's keys, each query's choice, one softmax (nn/lsa_buckets.py).""" pass # nn.exact_read: in this file raise NotImplementedError("this checkpoint's config does not use nn/lsa_buckets.py (left out of the export)") B, S = q.shape[:2] c = self.lsa doc = doc_ids.long() if doc_ids is not None else torch.zeros(B, S, dtype=torch.long, device=q.device) if key_valid is not None: doc = doc.masked_fill(~key_valid.bool(), -1) ds = doc_starts(doc) pos = torch.arange(S, device=q.device)[None] sink = (pos - ds < c["sinks"]) & (doc >= 0) opened, groups = None, None if not self.lsa_off: built = lsa_groups(k, doc, block=c["block"], per_block=c["per_block"], pool=c["pool"], cap=c["cap"], sinks=c["sinks"]) if built is not None: centroids, groups = built if self.open_impl == "list" and self.training: raise NotImplementedError("the list read is for evaluation (E33t stage C)") opened = lsa_open_table(q, centroids, groups, top_k=c["top_k"], width=c["width"], raw_window=c["window"], impl=self.open_impl) if self.flow is not None: self.flow.reading_lsa(self, q=q, k=k, v=v, doc=doc, key_valid=key_valid, opened=opened, sink=sink, window=c["window"]) return attend_lsa(q, k, v, doc=doc, key_valid=key_valid, backend=self.backend, opened=opened, window=c["window"], sink=sink, ds=ds, n_sinks=c["sinks"]) def _concept_read(self, q, k, v, x, *, doc_ids, key_valid): """E37: concepts of this call's keys (encoder), the reasoner's value update, each query's exact choice, and one softmax over sinks β€– block-aligned window β€– opened members β€– concept summaries (nn/concept_memory.py).""" pass # nn.concept_memory: in this file pass # nn.exact_read: in this file B, S = q.shape[:2] c = self.concept doc = doc_ids.long() if doc_ids is not None else torch.zeros(B, S, dtype=torch.long, device=q.device) if key_valid is not None: doc = doc.masked_fill(~key_valid.bool(), -1) ds = doc_starts(doc) pos = torch.arange(S, device=q.device)[None] sink = (pos - ds < c["sinks"]) & (doc >= 0) cidx, opened, dv, dv_tok = None, None, None, None if not self.concept_off: cidx = build_concepts(k, v, x if self.concept_reasoner is not None else None, doc, sink, block=c["block"], per_block=c["per_block"], iters=c["iters"], tau=c["tau"]) if cidx is not None: if self.concept_reasoner is not None: dv = self.concept_reasoner(cidx.z, cidx.block_of, cidx.c_doc) dv_tok = token_update(cidx, dv, S) opened = concept_open_table(q, cidx, top_k=c["top_k"], width=c["width"], variance=c["variance"]) if self.concept_stats is not None and cidx is not None: self.concept_stats = _concept_read_stats(q, cidx, opened, c) if self.flow is not None: self.flow.reading_concept(self, q=q, k=k, v=v, doc=doc, cidx=cidx, opened=opened, sink=sink) return attend_concepts(q, k, v, cidx=cidx, dv=dv, doc=doc, key_valid=key_valid, backend=self.backend, opened=opened, sink=sink, ds=ds, n_sinks=c["sinks"], summaries=c["summaries"], variance=c["variance"], dv_tok=dv_tok, sum_len=c.get("sum_len", 0)) @torch.no_grad() def _concept_read_stats(q, cidx, opened, c) -> dict: """E37 probe scalars: concept sizes (empty share, largest), and the share of queries whose budget is full.""" n = cidx.n out = {"concept/empty": float((n == 0).float().mean()), "concept/max_members": float(n.amax(-1).mean()), "concept/size_std": float(n.std(-1).mean())} if opened is not None: used = (opened.T.to(torch.int32) < int(opened.cap)).sum(-1).float() # concepts opened per query out["concept/opened_concepts"] = float(used.mean()) return out class SwiGLU(nn.Module): def __init__(self, d: int, ff: int): super().__init__() self.gate = nn.Linear(d, ff, bias=False) self.up = nn.Linear(d, ff, bias=False) self.down = nn.Linear(ff, d, bias=False) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x)) class Block(nn.Module): def __init__(self, cfg: PerceiverARConfig, layer_idx: int, pattern: str, window: int, has_skip: bool = False): super().__init__() self.attn_norm = nn.RMSNorm(cfg.hidden_size) self.attn = Attention(cfg, layer_idx, pattern, window) self.mlp_norm = nn.RMSNorm(cfg.hidden_size) self.mlp = SwiGLU(cfg.hidden_size, cfg.intermediate_size) # x0 re-injection (Ξ±=1, Ξ²=0 at init β†’ identity) and, only on layers that consume a # U-net skip, its weight Οƒ (0 at init). Layers without a skip get no Οƒ so every # parameter participates in every forward (DDP unused-parameter check). self.alpha = nn.Parameter(torch.tensor(1.0)) self.beta = nn.Parameter(torch.tensor(0.0)) self.sigma = nn.Parameter(torch.tensor(0.0)) if has_skip else None # E33: tied read β†’ update rounds on the exclusive global read. A zero-initialised # per-round embedding tells rounds apart; R = 1 is exactly today's block. rounds = int(getattr(cfg, "message_read_rounds", 1) or 1) self.read_rounds = rounds if (pattern == "full" and getattr(cfg, "message_enabled", False)) else 1 self.round_emb = nn.Parameter(torch.zeros(self.read_rounds, cfg.hidden_size)) if self.read_rounds > 1 else None self._collect_rounds = False self._round_outs: list = [] self.layer_idx = layer_idx self.flow = None # E33p instrumentation (nn/flow_stats.FlowRecorder) while armed def mix(self, x, x0, skip): """The residual-stream input this block's attention actually sees: x0 re-injection plus the U-net skip. Shared by `forward` and by `PerceiverARLM._run_layers(capture_input_of=)` so `prefix_kv` reconstructs the global layer's K/V exactly, wherever that layer sits.""" x = self.alpha * x + self.beta * x0 if skip is not None: if self.sigma is None: raise RuntimeError("skip passed to a layer built without a U-net skip weight") x = x + self.sigma * skip return x def forward(self, x, x0, skip, *, ids, cos, sin, key_valid, doc_ids, cu_seqlens, block_masks=None, sink_pos=None, pos=None, message=None, rope_theta=500000.0): x = self.mix(x, x0, skip) self._round_outs = [] rounds = self.read_rounds if message is not None else 1 frozen = message is not None and rounds > 1 and getattr(message, "slots", None) is None for r in range(rounds): if self.round_emb is not None: x = x + self.round_emb[r] a = self.attn(self.attn_norm(x), ids=ids, cos=cos, sin=sin, key_valid=key_valid, doc_ids=doc_ids, cu_seqlens=cu_seqlens, block_masks=block_masks, sink_pos=sink_pos, pos=pos, message=message, rope_theta=rope_theta) if self.flow is not None: self.flow.sublayer(self.layer_idx, "attn", x, a) x = x + a if torch.is_grad_enabled() or x.shape[1] <= _EVAL_FFN_CHUNK: f = self.mlp(self.mlp_norm(x)) else: # evaluation at 256k–1M: the feed-forward is per token, so pieces give the same result in less memory f = torch.cat([self.mlp(self.mlp_norm(x[:, i:i + _EVAL_FFN_CHUNK])) for i in range(0, x.shape[1], _EVAL_FFN_CHUNK)], dim=1) if self.flow is not None: self.flow.sublayer(self.layer_idx, "ffn", x, f) x = x + f if self._collect_rounds and r < rounds - 1: self._round_outs.append(x) if frozen and r == 0: # later rounds re-read the memory written in round 1 message.slots = getattr(self.attn, "_last_slots", None) if frozen: message.slots = None return x _EVAL_FFN_CHUNK = 1 << 17 # tokens per feed-forward piece without gradient (E33t stage C, 1M-token rows) def _call_block(layer, x, x0, skip, **kwargs): return layer(x, x0, skip, **kwargs) # Per-pass state of the message context that a reading layer reads or replaces. The backward's recomputation # (gradient checkpointing) runs after the loss has consumed and cleared it (index_losses, open_seen β†’ None) and after # later loop passes changed it (read_round, open_seen), so without the replay it would skip the index loss and save # fewer tensors than the original pass (CheckpointError, E33t 64k, our GPU server 2026-11-11). _REPLAY_FIELDS = ("index_losses", "open_seen", "read_round", "read_losses", "read_targets") def _replay_message_state(fn, ctx): """Wrap a checkpointed block call: the first call (the forward) runs as is; a recomputation first restores the message state the forward saw, then puts the current one back. The recomputed index loss is appended to the forward's own list, which the loss has already read, so it changes no result.""" state = {f: getattr(ctx, f, None) for f in _REPLAY_FIELDS} calls = [0] def run(*args): calls[0] += 1 if calls[0] == 1: return fn(*args) now = {f: getattr(ctx, f, None) for f in _REPLAY_FIELDS} for f, v in state.items(): setattr(ctx, f, v) try: return fn(*args) finally: for f, v in now.items(): setattr(ctx, f, v) return run # -------------------------------------------------------------------------------------- # Chunked soft-capped CE (+ z-loss) β€” never materialises [B,S,V] # -------------------------------------------------------------------------------------- @torch.no_grad() def per_token_ce_chunked(hidden, weight, labels, block_size, softcap) -> torch.Tensor: """Per-position CE [B,S] (0 where label == -100) without materialising [B,S,V].""" B, S, H = hidden.shape out = hidden.new_zeros((B, S), dtype=torch.float32) bs = block_size if block_size and block_size > 0 else S for s in range(0, S, bs): e = min(s + bs, S) logits = F.linear(hidden[:, s:e], weight).float() if softcap and softcap > 0: logits = softcap * torch.tanh(logits / softcap) V = logits.shape[-1] ce = F.cross_entropy( logits.reshape(-1, V), labels[:, s:e].reshape(-1), ignore_index=-100, reduction="none" ) out[:, s:e] = ce.view(B, e - s) return out def _chunk_ce(hidden, weight, labels, softcap, z_coef): logits = F.linear(hidden, weight).float() if softcap and softcap > 0: logits = softcap * torch.tanh(logits / softcap) V = logits.shape[-1] flat, lab = logits.reshape(-1, V), labels.reshape(-1) ce = F.cross_entropy(flat, lab, ignore_index=-100, reduction="sum") valid = lab != -100 if z_coef and z_coef > 0: lse = torch.logsumexp(flat, dim=-1) z = (lse.square() * valid).sum() * z_coef else: z = ce.new_zeros(()) return ce, z, valid.sum() def chunked_softcap_ce(hidden, weight, labels, block_size, softcap, z_coef): """Sum-CE, sum-z-loss and count over chunks; chunks are re-computed in backward.""" B, S, H = hidden.shape ce_tot = hidden.new_zeros((), dtype=torch.float32) z_tot = hidden.new_zeros((), dtype=torch.float32) n_tot = torch.zeros((), dtype=torch.long, device=hidden.device) bs = block_size if block_size and block_size > 0 else S for s in range(0, S, bs): e = min(s + bs, S) hb, lb = hidden[:, s:e], labels[:, s:e] if hidden.requires_grad or weight.requires_grad: ce, z, n = torch_checkpoint(_chunk_ce, hb, weight, lb, softcap, z_coef, use_reentrant=False) else: ce, z, n = _chunk_ce(hb, weight, lb, softcap, z_coef) ce_tot, z_tot, n_tot = ce_tot + ce, z_tot + z, n_tot + n return ce_tot, z_tot, n_tot def _liger_flce(): try: from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss except Exception: # pragma: no cover return None return LigerFusedLinearCrossEntropyLoss class LoopControl(nn.Module): """E33c (2026-10-18): each loop round reads its next relation from the question β€” a MAC control unit (Hudson & Manning 2018, arXiv 1803.03067) on the tied read loop. Why: rounds share weights, and on E33q / E33qn the only round-specific input was the per-round embedding (~2 % of the state; remapping or zeroing it at exam time changed nothing). Trained on 1–2 teacher hops, the loop learned "after at most two teacher reads, read the home": on 3-hop compose it picks bridge 2's home 80–89 % of the time. Here, at every position t, round r attends over the last W words (t βˆ’ W + 1 … t, own document), queried by the previous control and the question summary at t: s_{r,h,i} = q_{r,h} Β· k_{h,i} / √dh + b_h(i βˆ’ P_{rβˆ’1,h}) P_{rβˆ’1}: the previous round's pointer (t at round 1) Ξ± = softmax_i(s); c_r = Ξ£_i Ξ±_i v_i; P_r = Ξ£_i Ξ±_i i; u_r = gate βŠ™ rmsnorm(W_o c_r) - b_h is learned over the key's offset from the previous pointer (linearly interpolated), so "the next relation word to the left of the one just read" is one rule at any hop count: a third "teacher of" applies it once more. - Words are the input layer's vectors by default, identical at every "teacher of", so c_r cannot count hops either. - u_r is added to round r's input and taken out again after the round: the instruction is that round's alone (a sum over rounds would grow with the hop count). - The gate starts at 0: a warm start from E33q / E33qn is unchanged at step 0. Shapes: words, summary [B,S,d] β†’ per round u [B,S,d]; control c [B,S,dc]; pointer (distance left of t) [B,S,H]. """ def __init__(self, cfg: PerceiverARConfig): super().__init__() d, dc, H = cfg.hidden_size, int(cfg.message_loop_control_dim), int(cfg.message_loop_control_heads) self.W, self.H, self.dh = int(cfg.message_loop_control_window), H, dc // H self.to_k = nn.Linear(d, dc, bias=False) self.to_v = nn.Linear(d, dc, bias=False) self.q_from_c = nn.Linear(dc, dc, bias=False) self.q_from_x = nn.Linear(d, dc, bias=False) self.out = nn.Linear(dc, d, bias=False) self.c0 = nn.Parameter(torch.randn(dc)) # the control before round 1 (rms-normed before use) # b_h(Ξ΄) for Ξ΄ = key βˆ’ pointer ∈ [βˆ’(Wβˆ’1), Wβˆ’1], stored at Ξ΄ + W βˆ’ 1 (+ one entry for the interpolation's edge) self.ptr_bias = nn.Parameter(torch.zeros(H, 2 * self.W)) self.gate = nn.Parameter(torch.zeros(d)) def start(self, words: torch.Tensor, summary: torch.Tensor, doc: Optional[torch.Tensor]) -> dict: """Once per forward: keys / values of every word (left-padded by W βˆ’ 1), the window mask, the summary's query part, c_0 and the round-1 pointer (at t). doc [B,S] (βˆ’1 = padding) or None (one document per row).""" B, S, _ = words.shape W, H, dh = self.W, self.H, self.dh w = F.rms_norm(words, (words.shape[-1],)) k = F.pad(self.to_k(w).view(B, S, H, dh), (0, 0, 0, 0, W - 1, 0)) # [B,S+Wβˆ’1,H,dh] v = F.pad(self.to_v(w).view(B, S, H, dh), (0, 0, 0, 0, W - 1, 0)) if doc is None: doc = torch.zeros(B, S, dtype=torch.long, device=words.device) dp = F.pad(doc, (W - 1, 0), value=-2) ok = torch.stack([dp[:, j:j + S] == doc for j in range(W)], -1) # [B,S,W]; slot Wβˆ’1 = t qx = self.q_from_x(F.rms_norm(summary, (summary.shape[-1],))).view(B, S, H, dh) return {"k": k, "v": v, "ok": ok, "qx": qx, "c": self.c0.to(qx.dtype).expand(B, S, -1), "ptr": torch.zeros(B, S, H, device=words.device)} def step(self, st: dict, capture: Optional[dict] = None) -> torch.Tensor: """One round: read the window, move the pointer, return u_r [B,S,d] (updates st["c"], st["ptr"]).""" W, H, dh = self.W, self.H, self.dh B, S = st["ok"].shape[:2] k, v, c, ptr = st["k"], st["v"], st["c"], st["ptr"] q = self.q_from_c(F.rms_norm(c, (c.shape[-1],))).view(B, S, H, dh) + st["qx"] s = torch.stack([(q * k[:, j:j + S]).sum(-1) for j in range(W)], -1).float() / math.sqrt(dh) # [B,S,H,W] # slot j holds key t βˆ’ (W βˆ’ 1) + j; its offset from the pointer t βˆ’ ptr is Ξ΄ = j βˆ’ (W βˆ’ 1) + ptr, i.e. table # index j + ptr: rows n = ⌊ptrβŒ‹ and n + 1 of the table's length-W windows, mixed by the fraction n = ptr.detach().floor().clamp(0, W - 1) f = (ptr - n).unsqueeze(-1) n = n.long() tab = self.ptr_bias.float().unfold(1, W, 1) # [H, W+1, W] hh = torch.arange(H, device=ptr.device) s = s + tab[hh, n] * (1 - f) + tab[hh, n + 1] * f a = torch.softmax(s.masked_fill(~st["ok"][:, :, None, :], float("-inf")), -1) # [B,S,H,W] av = a.to(v.dtype) c = sum(av[..., j, None] * v[:, j:j + S] for j in range(W)).reshape(B, S, H * dh) # [B,S,dc] st["c"] = c st["ptr"] = (a * torch.arange(W - 1, -1, -1, device=a.device, dtype=a.dtype)).sum(-1) if capture is not None and "q_pos" in capture: # exam probe: where each round's control looks qp = capture["q_pos"].to(a.device) rows = torch.arange(B, device=a.device)[:, None] capture.setdefault("control_attn", []).append(a[rows, qp].detach()) # [B,P,H,W] capture.setdefault("control_ptr", []).append(st["ptr"][rows, qp].detach()) # [B,P,H] u = F.rms_norm(self.out(c), (self.out.out_features,)) return self.gate.to(u.dtype) * u def loop_control_param_count(cfg: PerceiverARConfig) -> int: d, dc = cfg.hidden_size, int(cfg.message_loop_control_dim) W, H = int(cfg.message_loop_control_window), int(cfg.message_loop_control_heads) return 3 * d * dc + dc * dc + dc * d + dc + H * 2 * W + d # -------------------------------------------------------------------------------------- # Model # -------------------------------------------------------------------------------------- class PerceiverARLM(PreTrainedModel): config_class = PerceiverARConfig base_model_prefix = "perceiver_ar" supports_gradient_checkpointing = True _no_split_modules = ["Block"] def __init__(self, config: PerceiverARConfig): super().__init__(config) cfg = config self.embed = TinyHashedEmbedding(cfg) patterns = cfg.layer_patterns() n = len(patterns) n_skip = n // 2 # U-net: layers [0, n_skip) push skips; layers [n - n_skip, n) pop them in reverse. self.layers = nn.ModuleList( [Block(cfg, i, p, w, has_skip=(i >= n - n_skip)) for i, (p, w) in enumerate(patterns)] ) for j, i in enumerate(cfg.stack_indices): layer = self.layers[i] if cfg.nope_every and ((j + 1) % cfg.nope_every == 0): layer.attn.use_rope = False if cfg.block_attention_mode == "bidirectional": layer.attn.causal = False if cfg.global_nope: for i in cfg.resolved_global_positions: self.layers[i].attn.use_rope = False self.final_norm = nn.RMSNorm(cfg.hidden_size) if getattr(cfg, "lm_head_tied", False): self.lm_head = TiedFactorizedHead(self.embed.tok, cfg.hidden_size) else: self.lm_head = nn.Linear(cfg.hidden_size, cfg.vocab_size, bias=False) self.memory_writer = ( LatentMemoryWriter(cfg) if str(getattr(cfg, "message_write", "block_mean") or "block_mean") == "latent_memory" else None ) if cfg.write_back_hook: g, dh = cfg.num_kv_heads, cfg.head_dim self.write_back_proj = nn.Linear(cfg.hidden_size, 2 * g * dh, bias=False) # Text multi-hop (2026-10-17): note read-back, training only. From each note's value vΜ„ (what the reader gets) a # linear head names the tokens at the note's expected position βˆ’1, 0, +1. On the bridge data the writer kept # names and places but dropped common words: the notes on "shiny" in "Every kavi is shiny." did not say which # property it was (probe 11 %, guessing 8 %), so deduce could not be answered however well the read aimed. self.note_readback = ( nn.Linear(int(cfg.lm_reader_tokens) * cfg.num_kv_heads * cfg.head_dim, 3 * cfg.vocab_size, bias=False) if self.memory_writer is not None and float(getattr(cfg, "lm_readback_aux", 0.0) or 0.0) > 0 else None ) self._readback_inputs = None # E33a: tied loop over [global read + span layers]. Zero-init loop marker β†’ R = 1 is today's stack. self.loop_rounds = int(getattr(cfg, "message_loop_rounds", 1) or 1) self.loop_emb = nn.Parameter(torch.zeros(self.loop_rounds, cfg.hidden_size)) if self.loop_rounds > 1 else None self.loop_gate = ( nn.Parameter(torch.zeros(())) if self.loop_rounds > 1 and getattr(cfg, "message_loop_inject", "none") == "prelude" else None ) self._loop_rounds_override: Optional[int] = None # eval: run r loops (exit r == the R = r forward) # E33q: the loop asks its next question with the name it found. Round r's state is read through the shared LM # head (final norm β†’ lm_head); the distribution, re-embedded with the shared token table and the input layer's # up-projection, joins round r+1's input through a per-channel gate that starts at 0 (step 0 = E33r). The # oracle of 17 Oct: E33r composes 58 % at 4k, 81 % with the bridge written into the question. if str(getattr(cfg, "message_loop_feedback", "none") or "none") not in ("none", "soft"): raise ValueError("message_loop_feedback must be 'none' or 'soft'") self.loop_feedback_gate = ( nn.Parameter(torch.zeros(cfg.hidden_size)) if self.loop_rounds > 1 and getattr(cfg, "message_loop_feedback", "none") == "soft" else None ) self._name_lens_losses: Optional[list] = None # E33c: each round reads its next relation from the question (LoopControl; gate from 0, step 0 = E33qn). # `_control_capture` = {"q_pos": [B,P]} records each round's control attention and pointer there (exam probe). self.loop_control = ( LoopControl(cfg) if self.loop_rounds > 1 and getattr(cfg, "message_loop_control", "none") == "question" else None ) self._control_capture: Optional[dict] = None # Notes-budget exam (latent memory, nothing retrained): `_notes_override` = (kΜ„, vΜ„, slot_pos) replaces what the # writer would write (another forward's notes: B reads A's notebook over its own text); `_note_keep` [B,nb] # hides every other note; `_note_capture` = {"q_pos": [B,P]} records how much each read looks at each note. # `_last_notes` holds the notes of the last forward when a capture or override is set. `_notes_external`: the # override is any number of notes written before this row (agent B's short question row reads agent A's # notebook; `write_notes` makes it), all readable from the row's first token. self._notes_override: Optional[tuple] = None self._notes_external = False # True: the override is a whole notebook read from before this row (agent B) self._note_keep: Optional[torch.Tensor] = None self._note_capture: Optional[dict] = None self._last_notes: Optional[tuple] = None # E33: whole-name loss. A linear probe showed round 1 names the bridge node only by its first letters # while the memory is addressed by the tail of a name; this head asks every loop state, at the decision # position, to name its node completely (all `message_loop_name_len` letters), so the next round can query. nl = int(getattr(cfg, "message_loop_name_len", 0) or 0) self.loop_name_head = ( nn.Linear(cfg.hidden_size, nl * cfg.vocab_size) if self.loop_rounds > 1 and float(getattr(cfg, "message_loop_name_aux", 0.0) or 0.0) > 0 and nl > 0 else None ) self._collect_name_states = False self._loop_core_states = None self._read_targets: Optional[torch.Tensor] = None self._loop_states: Optional[list] = None self._collect_loop_states = False self.gradient_checkpointing = False self._flce = None # default "real"; a no-notebook control (E31c) keeps "none" in its saved config, so evals of # its checkpoint never switch on an untrained writer self._message_override = str(getattr(config, "message_override", "real") or "real") self._open_eval = "on" # E33p eval switch (`open_override`) self.flow_recorder = None # E33p instrumentation: armed for one forward by training/flow_callback.py self._last_message_ctx = None self._last_prefix_ae = None if cfg.message_prefix_ae: self.prefix_ae_head = PrefixAEHead( cfg.num_kv_heads, cfg.head_dim, cfg.message_compress_ratio, cfg.vocab_size, ) else: self.prefix_ae_head = None self.post_init() # Zero-init the residual-writing projections (muP-like, modded-nanogpt). # At seqβ‰₯512 the 1/S attention mass is too small to open a dead `wo`; the probe can # disable this (see `zero_init_residuals=False`) without changing E18 checkpoints. if cfg.zero_init_residuals: for layer in self.layers: nn.init.zeros_(layer.attn.wo.weight) nn.init.zeros_(layer.mlp.down.weight) if cfg.write_back_hook: nn.init.zeros_(self.write_back_proj.weight) for layer in self.layers: if layer.attn.compressor is not None and getattr(layer.attn.compressor, "delta", None) is not None: nn.init.zeros_(layer.attn.compressor.delta.weight) # post_init re-inits Linears if getattr(layer.attn, "concept_reasoner", None) is not None: nn.init.zeros_(layer.attn.concept_reasoner.out.weight) # E37: the read starts as the summary read if self.memory_writer is not None: nn.init.zeros_(self.memory_writer.to_v_state.weight) # E31: values start as content if getattr(self.memory_writer, "keyread_out", None) is not None: nn.init.zeros_(self.memory_writer.keyread_out.weight) # the address read adds nothing at step 0 if self.note_readback is not None: # a zero head sends no gradient into the notes at step 0, so a warm-started reader keeps its decoding while the # head learns (a random head scrambled the values: E33b run 1 at half its run, 17 Oct, compose 60 β†’ 12 %) nn.init.zeros_(self.note_readback.weight) for layer in self.layers: if getattr(layer.attn, "note_counter", None) is not None: # E33h: the count adds nothing at step 0 nn.init.zeros_(layer.attn.note_counter.out.weight) if getattr(layer.attn, "note_order_gate", None) is not None: # E33i: switch nearly off (Οƒ(βˆ’2) β‰ˆ 0.12) nn.init.zeros_(layer.attn.note_order_gate.weight) nn.init.constant_(layer.attn.note_order_gate.bias, -2.0) # -- HF plumbing ---------------------------------------------------------------- def _init_weights(self, module): std = self.config.init_std if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=std) def get_input_embeddings(self): return self.embed.tok def set_input_embeddings(self, value): self.embed.tok = value def get_output_embeddings(self): return self.lm_head def _head_parts(self): """(output matrix, map applied to the final hidden state before it): ([V, H], identity) for the plain head, ([V, e] table, the projection) for the tied head, so the loss multiplies [.., e] by [V, e] (no [V, H] matrix).""" if isinstance(self.lm_head, TiedFactorizedHead): return self.lm_head.table, self.lm_head.project return self.lm_head.weight, (lambda x: x) def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None): self.gradient_checkpointing = True def gradient_checkpointing_disable(self): self.gradient_checkpointing = False @property def global_kv_space(self) -> tuple[int, int]: """(kv_heads, head_dim) of the global read layer β€” the message/prefix format.""" return self.config.num_kv_heads, self.config.head_dim @property def full_layer_indices(self) -> list[int]: """Layers currently attending with the unbounded `full` pattern (the global read in perceiver mode; every layer in dense mode).""" return [i for i, l in enumerate(self.layers) if l.attn.pattern == "full"] @contextmanager def reach_override(self, window: Optional[int]): """Eval-time reach ablation (E18 P3 instrument): for the duration of the block every `full` layer attends as `swa(window)` instead β€” the global read(s) in perceiver mode, every layer in dense mode. `window=None` is a no-op. Weights, tokens and the local stack are untouched, so a paired comparison against the unrestricted model isolates how much the loss at position p depends on *direct* access to keys further than `window` back. Positions p < window see exactly the same keys and therefore compute exactly the same loss β€” a built-in check for the probe. Yields the list of touched layer indices.""" if window is None: yield [] return if int(window) < 1: raise ValueError("reach_override window must be >= 1 or None") originals: list[tuple[int, str, int]] = [] for i in self.full_layer_indices: attn = self.layers[i].attn originals.append((i, attn.pattern, attn.window)) attn.pattern, attn.window = "swa", int(window) try: yield [i for i, _, _ in originals] finally: for i, pat, win in originals: self.layers[i].attn.pattern, self.layers[i].attn.window = pat, win @contextmanager def message_override(self, mode: Optional[str]): """E21 probe control for the message channel: `none` (receivers get no slots β€” the floor; sparse anchors still join if `message_global_anchors` is on β€” E27 anchors-only), `swapped` (slots of the neighbouring batch row β€” a wrong message), `raw` (receivers read the uncompressed prefix K/V across the boundary β€” the ceiling), `real` / None (no-op). Local layers stay severed in every mode unless `message_keep_local_swa`, so the paired differences isolate the channel. Slots-only is `real` with `message_global_anchors=none`. """ if mode in (None, "real"): yield return if mode not in ("none", "swapped", "raw"): raise ValueError(f"unknown message_override {mode!r}") prev = self._message_override self._message_override = mode try: yield finally: self._message_override = prev @contextmanager def open_override(self, mode: Optional[str]): """E33p eval switch for the exact read: `off` (no opened tokens: notes as gist + window; the LSA arm reads its sinks + window only), `gist_off` (opened tokens + window, the notes masked; the index still scores with ΞΊ), `on` / None (no-op). Combine with `message_override("none")` for the window only. E33t: `reuse` (a loop pass may re-open the notes earlier passes opened: the pass exclusion off).""" if mode in (None, "on"): yield return if mode not in ("off", "gist_off", "reuse"): raise ValueError(f"unknown open_override {mode!r}") prev = self._open_eval lsa = [l.attn for l in self.layers if getattr(l.attn, "lsa", None) is not None] prev_lsa = [a.lsa_off for a in lsa] self._open_eval = mode for a in lsa: a.lsa_off = mode == "off" try: yield finally: self._open_eval = prev for a, v in zip(lsa, prev_lsa): a.lsa_off = v @contextmanager def open_impl(self, impl: Optional[str]): """E33t stage C eval switch: `list` keeps each query's choice as a list and reads per query chunk (nn.exact_read.ChoiceList, `attend_list`): memory linear in the length, for 128k–1M; `table` / None: the [B, S, G] table (training, and the reference the list read is tested against).""" if impl in (None, "table"): yield return if impl != "list": raise ValueError(f"unknown open_impl {impl!r}") attns = [l.attn for l in self.layers] prev = [getattr(a, "open_impl", "table") for a in attns] for a in attns: a.open_impl = impl try: yield finally: for a, v in zip(attns, prev): a.open_impl = v def _set_flow(self, rec) -> None: for layer in self.layers: layer.flow = rec layer.attn.flow = rec def _note_index(self, out: dict, msg: MessageCtx, S: int): """E33p: the per-forward note index (tied keys' assignment, and what opens) after the writer.""" pass # nn.exact_read: in this file cfg = self.config geo = self.memory_writer.geometry(S) B = msg.doc.shape[0] n_w, K, W = geo.n_windows, geo.latents, geo.window if out.get("assign") is None: raise RuntimeError("lm_note_key='tied' needs the writer's competition assignment") A = out["assign"].float().mean(1).reshape(B, n_w, K, W) starts = torch.tensor(geo.starts, device=msg.doc.device, dtype=torch.long) page_tok = (starts[:, None] + torch.arange(W, device=msg.doc.device)[None]).clamp(max=S - 1) mode = str(cfg.lm_open) pick = msg.window_valid.bool() if msg.window_valid is not None else torch.ones(B, n_w, W, dtype=torch.bool, device=A.device) labels = None if str(getattr(cfg, "lm_filing", "argmax")) == "balanced": # E33t: balanced filing (ΞΊ uses the balanced Γ‚) pass # nn.exact_read: in this file A = balance_assign(A, pick, int(cfg.lm_filing_iters)) labels = file_capped(A, pick, cap=int(cfg.lm_filing_cap)) groups = None if mode != "none": groups = note_groups(A, pick, list(geo.starts), S=S, doc_start=doc_starts(msg.doc), slot_close=msg.slot_close, slot_doc=msg.slot_doc, mode=mode, labels=labels) if labels is not None and self.layers[cfg.global_layer_index].attn.flow is not None: self.layers[cfg.global_layer_index].attn.flow.filing(labels, pick, K) return NoteOpen(assign=A, page_tok=page_tok, groups=groups, mode=mode, k=int(cfg.lm_open_k), cap=int(cfg.lm_open_cap), per_page=K, read=str(getattr(cfg, "lm_note_read", "gist")), score=str(getattr(cfg, "lm_open_score", "sum_softmax")), levels=int(getattr(cfg, "lm_open_levels", 1) or 1), keep_pages=int(getattr(cfg, "lm_open_pages", 16)), new_per_pass=bool(getattr(cfg, "lm_open_new_per_pass", False)), labels=labels, pick=pick) # -- E21 message geometry --------------------------------------------------------- @staticmethod def _doc_starts(doc: torch.Tensor) -> torch.Tensor: starts = torch.ones_like(doc, dtype=torch.bool) starts[:, 1:] = doc[:, 1:] != doc[:, :-1] return starts def _swp_slot_tensors( self, side: torch.Tensor, doc: torch.Tensor, pos: torch.Tensor, key_valid: Optional[torch.Tensor], ): """Window banks β†’ slot_doc/side/pos, pool_valid [B,S] and window_valid [B,n_w,W]. Each window pools only its own earliest side of one document (`window_pick`), computed per window. `pool_valid` (the union) is kept for diagnostics; the compressor uses `window_valid`, which closes the E30 leak where a straddling window pooled receiver tokens that were poolable only in a later, receiver-only window. """ B, S = side.shape geo = swp_geometry(self.config, S) device = side.device n_w, W, K = geo.n_windows, geo.window, geo.bank_size tok_c, pick, slot_doc_w, slot_side_w, _has = window_pick(side, doc, key_valid, geo.starts, W) slot_doc = slot_doc_w.repeat_interleave(K, dim=1) slot_side = slot_side_w.repeat_interleave(K, dim=1) starts = torch.tensor(geo.starts, device=device, dtype=torch.long) page = max(W // max(K, 1), 1) qix = torch.arange(K, device=device) off = (qix + 1) * page - 1 pos_idx = (starts[:, None] + off[None, :]).clamp(0, S - 1).reshape(-1) slot_pos = pos.index_select(1, pos_idx) pool_valid = torch.zeros(B, S, dtype=torch.bool, device=device) if bool(pick.any()): b_ix = torch.arange(B, device=device)[:, None, None].expand_as(pick) tok_exp = tok_c[None].expand(B, n_w, W) pool_valid[b_ix[pick], tok_exp[pick]] = True return slot_doc, slot_side, slot_pos, pool_valid, pick def _lm_slot_tensors(self, side, doc, pos, key_valid): """E31 geometry β†’ slot_doc/side (per reader entry), a placeholder slot_pos (overwritten by the writer's expected positions) and slot_close [B, nb]: the row index of the last token each window wrote from (E31c closed read: readable by tokens at or after it).""" B, S = side.shape geo = lm_geometry(self.config, S) tok, pick, slot_doc_w, slot_side_w, _has = window_pick(side, doc, key_valid, geo.starts, geo.window) rep = geo.latents * geo.reader_tokens slot_doc = slot_doc_w.repeat_interleave(rep, dim=1) slot_side = slot_side_w.repeat_interleave(rep, dim=1) slot_pos = torch.zeros_like(slot_doc) last = torch.where(pick, tok[None].expand_as(pick), torch.full_like(pick, -1, dtype=torch.long)).amax(-1) slot_close = last.repeat_interleave(rep, dim=1) # βˆ’1 only where the window wrote nothing (slot_doc βˆ’1) return slot_doc, slot_side, slot_pos, pick, slot_close def _message_context( self, input_ids: torch.Tensor, doc_ids: Optional[torch.Tensor], key_valid: Optional[torch.Tensor], pos: torch.Tensor, external: Optional[tuple] = None, ) -> Optional[MessageCtx]: """Build the boundary geometry, or None when nothing in the batch is a receiver.""" cfg = self.config B, S = input_ids.shape dev = input_ids.device r = cfg.message_compress_ratio self._last_message_ctx = None doc = doc_ids.clone() if doc_ids is not None else torch.zeros(B, S, dtype=torch.long, device=dev) if key_valid is not None: doc = doc.masked_fill(~key_valid.bool(), -1) if external is not None: k_bar, v_bar, slot_pos = external nb = k_bar.shape[1] side = torch.ones(B, S, dtype=torch.long, device=dev) return MessageCtx( side=side, doc=doc, local_doc_ids=doc, slot_doc=torch.zeros(B, nb, dtype=torch.long, device=dev), slot_side=torch.zeros(B, nb, dtype=torch.long, device=dev), slot_pos=slot_pos.to(dev).expand(B, nb) if slot_pos.dim() == 1 else slot_pos.to(dev), n_sides=2, override=self._message_override, external=(k_bar, v_bar), ratio=r, inplace=cfg.message_slots_inplace, inplace_raw_kv=cfg.message_inplace_raw_kv, extra_slot_attends=int(getattr(cfg, "message_extra_slot_attends", 0) or 0), update_slot_kv=bool(getattr(cfg, "message_update_slot_kv", False)), anchor=torch.zeros(B, S, dtype=torch.bool, device=dev), anchor_mode="none", raw_window=int(getattr(cfg, "message_raw_window", 0) or 0), ) closed = str(getattr(cfg, "lm_read", "exclusive")) == "closed" if cfg.message_boundary_token_id >= 0: is_b = input_ids == cfg.message_boundary_token_id else: is_b = torch.zeros_like(input_ids, dtype=torch.bool) if not closed and not bool(is_b.any()): return None starts = self._doc_starts(doc) cum = is_b.long().cumsum(dim=1) base = torch.cummax(torch.where(starts, cum - is_b.long(), torch.zeros_like(cum)), dim=1).values side = cum - base K = int(side.max().item()) + 1 if K > TAG_SIDES: raise ValueError(f"{K} sides in one document; the (doc, side) mask tag holds at most {TAG_SIDES}") if getattr(cfg, "message_keep_local_swa", False): local = doc else: local = torch.where(doc < 0, doc, doc * K + side) window_valid = None slot_close = None write = str(getattr(cfg, "message_write", "block_mean") or "block_mean") if write == "sw_perceiver": slot_doc, slot_side, slot_pos, pool_valid, window_valid = self._swp_slot_tensors( side, doc, pos, key_valid ) slot_pos_lo = None if str(getattr(cfg, "swp_slot_pos", "page")) in ("boundary", "scaled", "mixed"): pass # nn.latent_memory: in this file bnd = _boundary_pos(side, doc, pos, slot_doc, fallback=slot_pos) ref = int(getattr(cfg, "slot_pos_ref", 2048)) if cfg.swp_slot_pos == "mixed": slot_pos, slot_pos_lo = bnd, scaled_slot_pos(slot_pos, bnd, ref) else: slot_pos = bnd if cfg.swp_slot_pos == "boundary" else scaled_slot_pos(slot_pos, bnd, ref) elif write == "latent_memory": slot_doc, slot_side, slot_pos, window_valid, slot_close = self._lm_slot_tensors(side, doc, pos, key_valid) pool_valid = None else: nb = -(-S // r) pad = nb * r - S docp = F.pad(doc, (0, pad), value=-1).view(B, nb, r) sidep = F.pad(side, (0, pad), value=-1).view(B, nb, r) homog = (docp == docp[..., :1]).all(dim=2) & (sidep == sidep[..., :1]).all(dim=2) & (docp[..., 0] >= 0) slot_doc = torch.where(homog, docp[..., 0], torch.full_like(docp[..., 0], -1)) slot_side = torch.where(homog, sidep[..., 0], torch.zeros_like(sidep[..., 0])) end_idx = (torch.arange(nb, device=dev) * r + (r - 1)).clamp(max=S - 1) slot_pos = pos[:, end_idx] pool_valid = None if cfg.message_pool_remainder: first_doc, first_side = docp[..., 0], sidep[..., 0] same = ( (docp == first_doc[..., None]) & (sidep == first_side[..., None]) & (first_doc[..., None] >= 0) ) live = same.any(dim=2) slot_doc = torch.where(live, first_doc, torch.full_like(first_doc, -1)) slot_side = torch.where(live, first_side.clamp(min=0), torch.zeros_like(first_side)) pool_ok = same & live[..., None] pool_valid = pool_ok.reshape(B, nb * r)[:, :S] idx = torch.arange(r, device=dev) last = (same.to(torch.long) * (idx + 1)).amax(dim=2).clamp(min=1) - 1 end_abs = (torch.arange(nb, device=dev) * r + last).clamp(max=S - 1) slot_pos = pos.gather(1, end_abs) stride = int(getattr(cfg, "message_pack_stride", 0) or 0) if stride > 0 and not bool(getattr(cfg, "message_pool_remainder", False)): # QUERY-aligned leftover: sender tokens in [0, P % stride) do not fill a # complete pack ending at QUERY. r=1 identity would keep them; drop them # from exclusive slots unless remainder-on (keep as identity slots). is_q = torch.zeros(B, S, dtype=torch.bool, device=dev) is_q[:, 0] = side[:, 0] >= 1 is_q[:, 1:] = (side[:, 1:] >= 1) & (side[:, :-1] == 0) qpos = is_q.to(torch.long).argmax(dim=1) leftover = torch.where(is_q.any(dim=1), qpos % stride, torch.zeros_like(qpos)) tok = torch.arange(S, device=dev)[None, :] drop_tok = (tok < leftover[:, None]) & (side == 0) & (doc >= 0) drop_slot = F.pad(drop_tok, (0, pad), value=False).view(B, nb, r).all(dim=2) slot_doc = torch.where(drop_slot, torch.full_like(slot_doc, -1), slot_doc) anchor_mode = str(getattr(cfg, "message_global_anchors", "none") or "none") token_ids = tuple(int(x) for x in (getattr(cfg, "message_anchor_token_ids", ()) or ())) window = int(getattr(cfg, "message_anchor_window", MESSAGE_QUERY_NBHD_DEFAULT) or 0) key_len = int(getattr(cfg, "message_anchor_key_len", 0) or 0) anchor = build_message_anchors( input_ids, side, doc, mode=anchor_mode, token_ids=token_ids, window=window, key_len=key_len, ) ctx = MessageCtx(side=side, doc=doc, local_doc_ids=local, slot_doc=slot_doc, slot_side=slot_side, slot_pos=slot_pos, n_sides=K, override=self._message_override, slot_pos_lo=slot_pos_lo if write == "sw_perceiver" else None, pool_valid=pool_valid, ratio=r, inplace=cfg.message_slots_inplace, inplace_raw_kv=cfg.message_inplace_raw_kv, extra_slot_attends=int(getattr(cfg, "message_extra_slot_attends", 0) or 0), update_slot_kv=bool(getattr(cfg, "message_update_slot_kv", False)), anchor=anchor, anchor_mode=anchor_mode, window_valid=window_valid, raw_window=int(getattr(cfg, "message_raw_window", 0) or 0), read_rule="closed" if closed else "exclusive", slot_close=slot_close, slot_nope=write == "latent_memory" and str(getattr(cfg, "lm_slot_pos", "read")) == "reader", note_topk=int(getattr(cfg, "lm_read_topk", 0) or 0) if closed else 0, open_eval=self._open_eval) self._last_message_ctx = ctx return ctx # -- helpers ---------------------------------------------------------------------- @staticmethod def _positions(S: int, B: int, doc_ids: Optional[torch.Tensor], device) -> torch.Tensor: if doc_ids is None: return torch.arange(S, device=device)[None].expand(B, S) # position within document: reset at every doc boundary starts = torch.ones_like(doc_ids, dtype=torch.bool) starts[:, 1:] = doc_ids[:, 1:] != doc_ids[:, :-1] idx = torch.arange(S, device=device)[None].expand(B, S) start_idx = torch.where(starts, idx, torch.zeros_like(idx)) start_idx = torch.cummax(start_idx, dim=1).values return idx - start_idx def _pad_inputs(self, input_ids, attention_mask, labels, doc_ids): m = self.config.attn_pad_multiple S = input_ids.shape[1] if m <= 1 or S % m == 0: return input_ids, attention_mask, labels, doc_ids, S pad = m - (S % m) pid = self.config.pad_token_id input_ids = F.pad(input_ids, (0, pad), value=pid) if attention_mask is None: attention_mask = torch.ones_like(input_ids) attention_mask[:, S:] = 0 else: attention_mask = F.pad(attention_mask, (0, pad), value=0) if labels is not None: labels = F.pad(labels, (0, pad), value=-100) if doc_ids is not None: doc_ids = F.pad(doc_ids, (0, pad), value=-1) return input_ids, attention_mask, labels, doc_ids, S @staticmethod def _needs_key_mask(attention_mask: Optional[torch.Tensor], causal: bool) -> bool: """Right-padded batches need no key mask under causal attention: a valid query at position t only sees keys <= t, and every pad key sits after the last valid query. Pad query rows are garbage but their labels are -100. Left/interior padding or bidirectional blocks still need the explicit mask.""" if attention_mask is None or bool(attention_mask.all()): return False if not causal: return True m = attention_mask.to(torch.int64) right_padded = bool((m.cumprod(dim=1) == m).all()) return not right_padded def _run_layers(self, input_ids, attention_mask, doc_ids, cu_seqlens, capture_input_of: Optional[int] = None, message_kv: Optional[tuple] = None, position_offset: int = 0, prefix_embeds: Optional[torch.Tensor] = None): cfg = self.config B, S = input_ids.shape key_valid = None if self._needs_key_mask(attention_mask, cfg.block_attention_mode == "causal"): key_valid = attention_mask.bool() pos0 = self._positions(S, B, doc_ids, input_ids.device) pos = pos0 + int(position_offset) if position_offset else pos0 msg = None local_doc = doc_ids if cfg.message_enabled: msg = self._message_context(input_ids, doc_ids, key_valid, pos, external=message_kv) if msg is not None: local_doc = msg.local_doc_ids x0 = self.embed(input_ids, local_doc) if prefix_embeds is not None: # E35: the message vectors replace the placeholder embeddings P = prefix_embeds.shape[1] x0 = torch.cat([prefix_embeds.to(x0.dtype), x0[:, P:]], 1) if self.memory_writer is not None: if msg is not None and msg.external is None: if self._notes_override is not None: # notes-budget exam: another forward's notebook k_o, v_o, sp_o = self._notes_override if self._notes_external: # agent B: a notebook written elsewhere, all of it before this row nb_o = k_o.shape[1] d0 = msg.doc.clamp(min=0).amax(dim=1, keepdim=True) msg.slot_doc = d0.expand(B, nb_o).contiguous() msg.slot_side = torch.zeros_like(msg.slot_doc) msg.slot_close = torch.zeros_like(msg.slot_doc) # closed before the row's first token elif k_o.shape[1] != msg.n_slots: raise ValueError(f"notes override has {k_o.shape[1]} notes, this row's geometry {msg.n_slots}") msg.slots, msg.slot_pos = (k_o, v_o), sp_o else: out = self.memory_writer( self._writer_input(input_ids, msg.local_doc_ids), msg.side, msg.doc, key_valid, pos, cfg.rope_theta, ) msg.slots = (out["k"], out["v"]) msg.slot_pos = out["slot_pos"] if self.layers[0].flow is not None and out.get("assign") is not None: geo_f = self.memory_writer.geometry(S) self.layers[0].flow.writer_assign( out["assign"].float().mean(1).reshape(B, geo_f.n_windows, geo_f.latents, geo_f.window), msg.window_valid) if self.note_readback is not None and self.training: self._readback_inputs = (out["v"], out["slot_pos"], msg.slot_doc) if self._note_capture is not None or self._notes_override is not None: self._last_notes = (msg.slots[0], msg.slots[1], msg.slot_pos) if self._note_capture is not None: # requests score A's whole notebook, hidden notes included self._note_capture["slot_close_all"] = msg.slot_close if self._note_keep is not None: # a hidden note's window never closes for anyone msg.slot_close = msg.slot_close.masked_fill(~self._note_keep.to(msg.slot_close.device), -1) msg.capture = self._note_capture if str(getattr(cfg, "lm_note_key", "writer")) == "tied": if self._notes_override is not None: raise NotImplementedError("tied note keys (E33p) need this row's own writer pass") msg.index = self._note_index(out, msg, S) if self.training and float(getattr(cfg, "lm_index_loss", 0.0) or 0.0) > 0: msg.index_losses = [] # E33t: filled by the reading layer, one term per pass else: x0 = x0 + self.memory_writer.participation().to(x0.dtype) # DDP: no QUERY in batch if (msg is not None and msg.external is None and self.training and self._read_targets is not None and self.memory_writer is not None and float(getattr(cfg, "message_loop_read_aux", 0.0) or 0.0) > 0): geo = self.memory_writer.geometry(S) msg.read_targets = self._read_targets.to(input_ids.device) msg.read_round, msg.read_losses = 1, [] msg.page_starts = torch.tensor(geo.starts, device=input_ids.device, dtype=torch.long) msg.page_window, msg.notes_per_page = geo.window, geo.latents * geo.reader_tokens msg.read_target = str(getattr(cfg, "message_loop_read_target", "page") or "page") cos, sin = rope_cos_sin(pos, cfg.head_dim, cfg.rope_theta, x0.dtype) x = x0 n = len(self.layers) n_skip = n // 2 skips: list[torch.Tensor] = [] block_masks: Optional[dict] = {} if cfg.attn_backend == "flex" else None sink_pos = None if cfg.swa_sink and local_doc is not None: local_pos = pos0 if local_doc is doc_ids else self._positions(S, B, local_doc, input_ids.device) sink_pos = (torch.arange(S, device=input_ids.device)[None].expand(B, S) - local_pos) def run_layer(i, x, skips): layer = self.layers[i] skip = skips.pop() if (i >= n - n_skip and skips) else None is_global = layer.attn.pattern == "full" and ( layer.attn.compressor is not None or self.memory_writer is not None ) kwargs = dict(ids=input_ids, cos=cos, sin=sin, key_valid=key_valid, doc_ids=(doc_ids if is_global else local_doc), cu_seqlens=cu_seqlens, block_masks=block_masks, sink_pos=sink_pos, pos=pos, message=(msg if is_global else None), rope_theta=cfg.rope_theta) if self.gradient_checkpointing and self.training: fn = partial(_call_block, layer, **kwargs) if kwargs["message"] is not None: fn = _replay_message_state(fn, kwargs["message"]) x = torch_checkpoint(fn, x, x0, skip, use_reentrant=False) else: x = layer(x, x0, skip, **kwargs) if layer.flow is not None: layer.flow.residual(i, x) if i < n_skip: skips.append(x) return x self._loop_states = None R = int(self._loop_rounds_override or self.loop_rounds) if self.loop_emb is not None and capture_input_of is None: # E33a: prelude (once) β†’ core = [global read + span layers] Γ— R (tied) β†’ coda (once). gi = cfg.global_layer_index core = range(gi, gi + 1 + cfg.message_loop_span) for i in range(gi): x = run_layer(i, x, skips) prelude, skips0 = x, list(skips) ctrl, cst = self.loop_control, None if ctrl is not None: # E33c: the words the control reads, and their documents (βˆ’1 = padding) cdoc = local_doc if key_valid is not None: cdoc = (key_valid.long() - 1) if cdoc is None else cdoc.masked_fill(~key_valid, -1) words = prelude if cfg.message_loop_control_words == "prelude" else x0 cst = ctrl.start(words, prelude, cdoc) states = [] for r in range(R): if msg is not None: msg.read_round = r + 1 x = x + self.loop_emb[min(r, self.loop_emb.shape[0] - 1)].to(x.dtype) if r and self.loop_gate is not None: x = x + self.loop_gate.to(x.dtype) * prelude u = ctrl.step(cst, self._control_capture).to(x.dtype) if cst is not None else None if u is not None: x = x + u s = list(skips0) if self.layers[gi].flow is not None: self.layers[gi].flow.round = r for i in core: x = run_layer(i, x, s) if self.layers[gi].flow is not None: self.layers[gi].flow.round = None if u is not None: x = x - u # round r's instruction is its own; the next round gets the next one if not (self._collect_name_states or self._collect_loop_states): states = [] # only the last pass is used: 1M-token evals keep one copy, not one per pass states.append((x, s)) if r < R - 1 and (self.loop_feedback_gate is not None or self._name_lens_losses is not None): x = self._loop_lens(x, r, input_ids) if self._collect_name_states: self._loop_core_states = [xs for xs, _ in states] if self._collect_loop_states: # exits: each earlier loop's state through the answer layer exits = [] for xr, sr in states[:-1]: sr = list(sr) for i in range(core.stop, n): xr = run_layer(i, xr, sr) exits.append(xr) self._loop_states = exits skips = states[-1][1] for i in range(core.stop, n): x = run_layer(i, x, skips) return x for i, layer in enumerate(self.layers): if capture_input_of is not None and i == capture_input_of: skip = skips.pop() if (i >= n - n_skip and skips) else None return layer.mix(x, x0, skip) x = run_layer(i, x, skips) return x @torch.no_grad() def write_notes(self, input_ids: torch.Tensor, chunk_pages: int = 0) -> tuple: """Agent A: one document's notes (kΜ„, vΜ„, slot_pos) from the writer alone β€” the notebook the global read would see for this row (one unpadded document, [1, S]). The writer reads page text only, so nothing of the main stack runs. `chunk_pages` > 0: that many pages per pass (chunks cut at page starts, overlapping by window βˆ’ stride), the same notes as one pass, bounded memory (1M tokens).""" if self.memory_writer is None: raise RuntimeError("write_notes needs a latent-memory model") cfg = self.config if str(getattr(cfg, "lm_note_key", "writer")) == "tied": raise NotImplementedError("tied note keys (E33p) are the reading layer's own keys: no stand-alone notebook") B, S = input_ids.shape W, st = int(cfg.lm_window), int(cfg.lm_stride) def span(ids, off): side = torch.zeros_like(ids) pos = torch.arange(ids.shape[1], device=ids.device)[None].expand(B, -1) + off msg = self._message_context(ids, None, None, pos) out = self.memory_writer(self._writer_input(ids, msg.local_doc_ids), msg.side, msg.doc, None, pos, cfg.rope_theta) return out["k"], out["v"], out["slot_pos"] if not chunk_pages or B != 1 or S <= 2 * chunk_pages * st: return span(input_ids, 0) T, parts, s0 = chunk_pages * st, [], 0 while True: end = min(S, s0 + T + (W - st)) if S - end < W + st: # the last chunk absorbs a short tail (keeps the page geometry) end = S # a full chunk holds exactly `chunk_pages` windows, at the document's own page starts parts.append(span(input_ids[:, s0:end], s0)) if end == S: break s0 += T return tuple(torch.cat([p[i] for p in parts], 1) for i in range(3)) # -- forward ---------------------------------------------------------------------- def hidden_states( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, doc_ids: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Final-norm hidden states [B, S, d] without materialising logits. Probes that only need argmax at a few positions (passkey, copy) project `hidden_states(...)[:, positions]` with `lm_head.weight` themselves: full logits at S=32k are 16 GB in fp32 (S Γ— V), the hidden states are 50 MB. """ input_ids, attention_mask, _, doc_ids, S_orig = self._pad_inputs( input_ids, attention_mask, None, doc_ids ) x = self._run_layers(input_ids, attention_mask, doc_ids, None) return self.final_norm(x)[:, :S_orig] def forward( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, doc_ids: Optional[torch.Tensor] = None, cu_seqlens: Optional[torch.Tensor] = None, return_per_token_loss: bool = False, return_logits: bool = False, message_kv: Optional[tuple] = None, position_offset: int = 0, prefix_embeds: Optional[torch.Tensor] = None, read_targets: Optional[torch.Tensor] = None, ce_norm: Optional[torch.Tensor] = None, ): # NOTE: no **kwargs here on purpose. HF Trainer treats any VAR_KEYWORD forward as a # model that normalizes its own loss by num_items_in_batch and then skips the division # by gradient_accumulation_steps (loss and grad-clip off by accumΓ—). This forward # returns a per-microbatch mean; the Trainer must do the accumulation scaling. # # `ce_norm` (E37 SFT, the trainer's --loss_step_token_mean): divide the next-token CE SUM by this # instead of this micro-batch's own target count. PerceiverDenoiseTrainer passes the optimizer # step's target count / (accumulation steps x processes), so after the Trainer's division by # the accumulation steps and DDP's mean over processes the CE is the step's token mean, as # torchtitan computes it. z-loss and every auxiliary term keep their per-micro-batch weighting. # None: exactly the per-micro-batch mean (trunk, decay, every earlier run). # # `message_kv=(kΜ„, vΜ„, slot_pos)` + `position_offset=P` is the E21 receiver-only forward: # `input_ids` are the tokens from the boundary on, and the prefix is present only as the # given slots (what `prefix_kv(..., as_message=True)` returns). cfg = self.config round_tgt = getattr(self, "_round_targets", None) self._round_targets = None # text multi-hop (2026-10-17): per-question read targets from the collator, used in training only self._read_targets = read_targets if self.training else None # E33q: hop-naming losses collected by the loop rounds (training with read targets only) self._name_lens_losses = ([] if (self.training and read_targets is not None and labels is not None and float(getattr(cfg, "message_loop_name_lens", 0.0) or 0.0) > 0 and self.loop_emb is not None) else None) # Text (closed read): the exit aux is a training signal only, so eval loss stays the plain # next-token CE that every text-checks arm is compared on. Exam mode (exclusive) unchanged. self._collect_loop_states = bool( labels is not None and self.loop_emb is not None and cfg.message_loop_exit_aux > 0 and not return_per_token_loss and int(self._loop_rounds_override or self.loop_rounds) > 1 and (self.training or getattr(cfg, "lm_read", "exclusive") != "closed") ) self._collect_name_states = bool( labels is not None and self.loop_name_head is not None and not return_per_token_loss and int(self._loop_rounds_override or self.loop_rounds) > 1 ) self._loop_core_states = None looped = [b for b in self.layers if getattr(b, "read_rounds", 1) > 1] for b in looped: b._collect_rounds = round_tgt is not None if message_kv is not None and not cfg.message_enabled: raise RuntimeError("message_kv needs message_boundary_token_id >= 0") # E35 receiver: `prefix_embeds` [B, P, d] are read as the first P input positions (Cramming-style message # vectors, seen by every layer); they get no target and no output logits. P = 0 if prefix_embeds is not None: if cfg.message_enabled: raise RuntimeError("prefix_embeds is for a model without the E21 message boundary") B0, P = input_ids.shape[0], prefix_embeds.shape[1] input_ids = torch.cat([input_ids.new_full((B0, P), cfg.pad_token_id), input_ids], 1) if attention_mask is not None: attention_mask = torch.cat([attention_mask.new_ones((B0, P)), attention_mask], 1) if labels is not None: labels = torch.cat([labels.new_full((B0, P), -100), labels], 1) if doc_ids is not None: doc_ids = torch.cat([doc_ids[:, :1].expand(B0, P), doc_ids], 1) input_ids, attention_mask, labels, doc_ids, S_orig = self._pad_inputs( input_ids, attention_mask, labels, doc_ids ) rec = self.flow_recorder if (self.flow_recorder is not None and self.flow_recorder.armed) else None if rec is not None: # E33p: one instrumented forward rec.begin(input_ids) self._set_flow(rec) try: x = self._run_layers(input_ids, attention_mask, doc_ids, cu_seqlens, message_kv=message_kv, position_offset=position_offset, prefix_embeds=prefix_embeds) finally: if rec is not None: self._set_flow(None) rec.armed = False h = self.final_norm(x) head_w, head_in = self._head_parts() if labels is None or return_logits: logits = F.linear(head_in(h[:, P:S_orig]), head_w).float() if cfg.logit_softcap: logits = cfg.logit_softcap * torch.tanh(logits / cfg.logit_softcap) if labels is None: return CausalLMOutput(loss=None, logits=logits) # next-token targets: position t predicts labels[t+1] tgt = labels[:, 1:] hid = h[:, :-1] if return_per_token_loss: per = per_token_ce_chunked( head_in(hid), head_w, tgt, cfg.chunked_ce_block_size, cfg.logit_softcap )[:, P: S_orig - 1] valid = tgt[:, P: S_orig - 1] != -100 loss = per.sum() / valid.sum().clamp(min=1) return CausalLMOutput(loss=loss, logits=None), per, valid # Liger's fused loss returns CE + z-loss as one sum with its gradient built in, so the two cannot be scaled # apart. With ce_norm (the step's token mean for the CE, the z-loss kept per micro-batch) the chunked path # below is used instead, so both paths give ce / ce_norm + z / n (review of 2026-11-14). flce = self._get_flce() if (cfg.use_liger and hid.is_cuda and ce_norm is None) else None if flce is not None: n = (tgt != -100).sum().clamp(min=1) hin = head_in(hid) loss = flce(head_w, hin.reshape(-1, hin.shape[-1]), tgt.reshape(-1)) / n else: ce, z, n = chunked_softcap_ce( head_in(hid), head_w, tgt, cfg.chunked_ce_block_size, cfg.logit_softcap, cfg.z_loss ) if ce_norm is None: loss = (ce + z) / n.clamp(min=1) else: # the step's token mean for the CE; the z-loss stays this micro-batch's mean loss = ce / ce_norm + z / n.clamp(min=1) if round_tgt is not None and looped and cfg.message_round_aux > 0: outs = looped[0]._round_outs aux, k = loss.new_zeros(()), 0 for r, xr in enumerate(outs[: round_tgt.shape[0]]): tr = round_tgt[r] if tr.shape[1] < xr.shape[1]: tr = F.pad(tr, (0, xr.shape[1] - tr.shape[1]), value=-100) ce_r, _, n_r = chunked_softcap_ce(self.final_norm(xr)[:, :-1], self.lm_head.weight, tr[:, 1:], cfg.chunked_ce_block_size, cfg.logit_softcap, 0.0) aux, k = aux + ce_r / n_r.clamp(min=1), k + 1 if k: loss = loss + cfg.message_round_aux * aux / k looped[0]._round_outs = [] if self._collect_loop_states and self._loop_states: loss = loss + cfg.message_loop_exit_aux * self._loop_exit_loss(self._loop_states, labels, round_tgt) self._loop_states = None self._collect_loop_states = False if self._collect_name_states and self._loop_core_states: loss = loss + cfg.message_loop_name_aux * self._loop_name_loss(self._loop_core_states, labels, round_tgt) self._loop_core_states = None self._collect_name_states = False if self._readback_inputs is not None: loss = loss + cfg.lm_readback_aux * self._readback_loss(input_ids, attention_mask) self._readback_inputs = None if float(getattr(cfg, "lm_count_aux", 0.0) or 0.0) > 0 and self.training and read_targets is not None: loss = loss + cfg.lm_count_aux * self._count_loss(read_targets) if self._name_lens_losses: loss = loss + cfg.message_loop_name_lens * torch.cat(self._name_lens_losses).mean() self._name_lens_losses = None mctx = self._last_message_ctx rls = getattr(mctx, "read_losses", None) if mctx is not None else None if rls: loss = loss + cfg.message_loop_read_aux * torch.cat(rls).mean() ils = getattr(mctx, "index_losses", None) if mctx is not None else None if ils: # E33t: the catalogue learns where the read's attention lands loss = loss + float(cfg.lm_index_loss) * torch.stack(ils).mean() if mctx is not None: mctx.read_losses, mctx.read_targets = None, None mctx.index_losses, mctx.open_seen = None, None self._read_targets = None loss = self._maybe_add_prefix_ae(loss, input_ids) return CausalLMOutput(loss=loss, logits=(logits if return_logits else None)) def _count_loss(self, read_targets: torch.Tensor) -> torch.Tensor: """E33k: at each count question's decision position (a quad with round == COUNT_ROUND marks it) every count head's sum n (the last loop round's read) must equal the true number of visits (quads with rounds COUNT_ROUND + 1 …): Huber(n βˆ’ k), mean over heads and questions. 0 if the batch has no count question.""" try: from data.text_world import COUNT_ROUND except ImportError as e: # not part of the Hub export raise ImportError("data.text_world belongs to the MrCogito training code (https://github.com/ksopyla/MrCogito)") from e att = self.layers[self.config.global_layer_index].attn n = getattr(getattr(att, "note_counter", None), "last_n", None) rt = read_targets.to(n.device) if n is not None else None if n is None or rt is None or not bool((rt[..., 1] == COUNT_ROUND).any()): return (n.sum() * 0.0) if n is not None else torch.zeros((), device=read_targets.device) bi, ti = (rt[..., 1] == COUNT_ROUND).nonzero(as_tuple=True) qp = rt[bi, ti, 0] visits = ((rt[..., 1] > COUNT_ROUND) & (rt[..., 1] < 2 * COUNT_ROUND)) # [B,T] same = (rt[bi, :, 0] == qp[:, None]) & visits[bi] # [N,T] k = same.sum(-1).float() # [N] got = n[bi, qp] # [N,nc] return F.smooth_l1_loss(got.float(), k[:, None].expand_as(got)) def _writer_input(self, ids: torch.Tensor, local_doc: Optional[torch.Tensor]) -> torch.Tensor: """What the notebook writer reads: the shared token table [B,S,e], or with lm_writer_input="embed" the decoder's whole input layer [B,S,d] (the same encoding the reader's tokens start from).""" if getattr(self.config, "lm_writer_input", "table") == "embed": return self.embed(ids, local_doc) return self.embed.tok(ids) def _loop_lens(self, x: torch.Tensor, r: int, input_ids: torch.Tensor) -> torch.Tensor: """E33q, after loop round r (0-based, not the last): the round's state through the shared LM head, with the decoder weights DETACHED (final norm, LM head, token table, input up-projection), so neither the naming loss nor the feedback trains the output head or the encoding the writer reads; only the loop's state and the gate learn. - Training with read targets (`message_loop_name_lens` > 0): at each question's decision position the distribution must name hop r+1's output word β€” the tokens of its span (quads with round == r + 1: answer position, round, first token, last token), βˆ’mean log p; spans longer than 4 tokens (quote's signs, the builder's whole-sentence fallback) are skipped. All the word's pieces, not just the first: a name's first piece is its capital letter, which a dozen cast members share. Appended to `_name_lens_losses`. - `message_loop_feedback="soft"`: softmax(logits / T) @ token table β†’ the input layer's up-projection and norm β†’ Γ— the per-channel gate (starts at 0) β†’ added to the state that enters round r + 1. [B,S,d] β†’ [B,S,d].""" cfg = self.config fn = self.final_norm h = F.rms_norm(x, fn.normalized_shape, fn.weight.detach() if fn.weight is not None else None, fn.eps) W_out = self.lm_head.weight.detach() sc = float(cfg.logit_softcap or 0.0) cap = (lambda z: sc * torch.tanh(z / sc)) if sc > 0 else (lambda z: z) rt = self._read_targets if self._name_lens_losses is not None and rt is not None: rt = rt.to(x.device) sel = ((rt[..., 1] == r + 1) & (rt[..., 0] >= 0) & (rt[..., 2] >= 0) & (rt[..., 3] - rt[..., 2] + 1 <= 4) & (rt[..., 3] >= rt[..., 2])) if bool(sel.any()): bi, ti = sel.nonzero(as_tuple=True) qp, t0, t1 = rt[bi, ti, 0], rt[bi, ti, 2], rt[bi, ti, 3] logp = F.log_softmax(cap(F.linear(h[bi, qp], W_out).float()), -1) # [N,V] off = torch.arange(4, device=x.device) tp = t0[:, None] + off[None] # [N,4] ok = tp <= t1[:, None] tok = input_ids[bi[:, None], tp.clamp(max=input_ids.shape[1] - 1)] nll = -(logp.gather(1, tok) * ok).sum(-1) / ok.sum(-1).clamp(min=1) self._name_lens_losses.append(nll) if self.loop_feedback_gate is None: return x p = torch.softmax(cap(F.linear(h, W_out)).float() / cfg.message_loop_feedback_temp, -1) E = self.embed e = p.to(E.tok.weight.dtype) @ E.tok.weight.detach() # [B,S,e] up = F.linear(e, E.up0.weight.detach()) + F.linear(F.silu(F.linear(e, E.up1.weight.detach())), E.up2.weight.detach()) fb = F.rms_norm(up, E.norm.normalized_shape, E.norm.weight.detach() if E.norm.weight is not None else None, E.norm.eps) return x + self.loop_feedback_gate.to(x.dtype) * fb.to(x.dtype) def _readback_loss(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor]) -> torch.Tensor: """Mean CE of naming, from each live note's value, the tokens at its expected position βˆ’1, 0, +1.""" v, sp, sd = self._readback_inputs B, C = sp.shape V = int(self.config.vocab_size) S = input_ids.shape[1] p = self.note_readback.weight.shape[0] // V logits = self.note_readback(v.reshape(B, C, -1)).view(B, C, p, V) off = torch.arange(p, device=sp.device) - (p // 2) pos = sp[:, :, None] + off[None, None] # [B,C,p] ok = (sd[:, :, None] >= 0) & (pos >= 0) & (pos < S) pc = pos.clamp(0, S - 1) tgt = input_ids.gather(1, pc.reshape(B, -1)).view(B, C, p) if attention_mask is not None: ok = ok & attention_mask.bool().gather(1, pc.reshape(B, -1)).view(B, C, p) if not bool(ok.any()): return logits.sum() * 0.0 return F.cross_entropy(logits[ok].float(), tgt[ok]) def _loop_exit_loss(self, exits: list, labels: torch.Tensor, round_tgt: Optional[torch.Tensor]) -> torch.Tensor: """E33a: Ξ£ over non-final loop exits of the token-mean CE. Exit r's targets are the round targets (`set_round_targets`, chain node r+1) or, with `message_loop_exit_targets="answer"` or none given, the labels.""" cfg = self.config total = labels.new_zeros((), dtype=torch.float32) base = labels if getattr(cfg, "message_loop_exit_mask", "all") == "answers": # text multi-hop (2026-10-17): exits score only the first answer token of every question (the decision) base = torch.full_like(labels, -100) rt = self._read_targets if rt is not None: rt = rt.to(labels.device) b, t = ((rt[..., 1] == 0) & (rt[..., 0] >= 0) & (rt[..., 0] + 1 < labels.shape[1])).nonzero(as_tuple=True) pos = rt[b, t, 0] + 1 base[b, pos] = labels[b, pos] for r, xr in enumerate(exits): tr = base if cfg.message_loop_exit_targets == "progress" and round_tgt is not None and r < round_tgt.shape[0]: tr = round_tgt[r] if tr.shape[1] < labels.shape[1]: tr = F.pad(tr, (0, labels.shape[1] - tr.shape[1]), value=-100) ce_r, _, n_r = chunked_softcap_ce(self.final_norm(xr)[:, :-1], self.lm_head.weight, tr[:, 1:], cfg.chunked_ce_block_size, cfg.logit_softcap, 0.0) total = total + ce_r / n_r.clamp(min=1) return total def _loop_name_loss(self, states: list, labels: torch.Tensor, round_tgt: Optional[torch.Tensor]) -> torch.Tensor: """E33: mean over loop rounds of the CE of naming the round's node, all letters at once, from the state at the decision position (the position that predicts the first answer letter). Round r names node r+1 (round targets; the last round names the answer). Shapes: states r Γ— [B, S, d] β†’ logits [B, L, V].""" cfg = self.config B, S = labels.shape L, V = int(cfg.message_loop_name_len), int(cfg.vocab_size) m = labels != -100 has = m.any(-1) first = m.float().argmax(-1) dec = (first - 1).clamp(min=0) idx = first[:, None] + torch.arange(L, device=labels.device)[None] inb = idx < S idx = idx.clamp(max=S - 1) rows = torch.arange(B, device=labels.device) n_tg = round_tgt.shape[0] if round_tgt is not None else 0 total = labels.new_zeros((), dtype=torch.float32) for r, xr in enumerate(states): tr = labels if r < n_tg: tr = round_tgt[r] if tr.shape[1] < S: tr = F.pad(tr, (0, S - tr.shape[1]), value=-100) tr = tr[:, :S] h = self.final_norm(xr[rows, dec]) logits = self.loop_name_head(h).view(B, L, V).float() tgt = tr.gather(1, idx) valid = has[:, None] & inb & (tgt != -100) ce = F.cross_entropy(logits.reshape(-1, V), tgt.clamp(min=0).reshape(-1), reduction="none") total = total + (ce * valid.reshape(-1)).sum() / valid.sum().clamp(min=1) return total / max(len(states), 1) def set_round_targets(self, targets: Optional[torch.Tensor]) -> None: """E33: labels per non-final read round [R-1, B, S] for the next forward (then cleared).""" self._round_targets = targets def _maybe_add_prefix_ae(self, loss: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor: """Add Ξ» L_AE. Answer-span CE is unchanged; compressor grads come from AE only.""" cfg = self.config self._last_prefix_ae = None if not cfg.message_prefix_ae or self.prefix_ae_head is None: return loss gi = cfg.global_layer_index attn = self.layers[gi].attn k_bar = getattr(attn, "_last_k_bar", None) ctx = self._last_message_ctx if k_bar is None or ctx is None: return loss + 0.0 * self.prefix_ae_head.proj.weight.sum().to(loss.dtype) B, nb, g, dh = k_bar.shape r = max(int(ctx.ratio), 1) S = input_ids.shape[1] pad = nb * r - S ids_pad = F.pad(input_ids, (0, pad), value=-100) tgt = ids_pad.view(B, nb, r) valid = (ctx.slot_doc >= 0) & (ctx.slot_side == 0) tgt = tgt.masked_fill(~valid.unsqueeze(-1), -100) logits = self.prefix_ae_head(k_bar) V = logits.shape[-1] n = (tgt != -100).sum().clamp(min=1) ae = F.cross_entropy(logits.reshape(-1, V).float(), tgt.reshape(-1), ignore_index=-100, reduction="sum") / n pred = logits.argmax(-1) tok_ok = tgt != -100 tok_acc = (pred[tok_ok] == tgt[tok_ok]).float().mean() if bool(tok_ok.any()) else tgt.new_zeros(()) key_len = int(getattr(cfg, "message_anchor_key_len", 0) or 0) token_ids = tuple(int(x) for x in (getattr(cfg, "message_anchor_token_ids", ()) or ())) key_acc = tok_acc if token_ids: key_mask = build_message_anchors( input_ids, ctx.side, ctx.doc, mode="key_spans", token_ids=token_ids, key_len=key_len, ) key_pad = F.pad(key_mask, (0, pad), value=False).view(B, nb, r) key_ok = key_pad & tok_ok if bool(key_ok.any()): key_acc = (pred[key_ok] == tgt[key_ok]).float().mean() else: key_acc = tgt.new_zeros(()) self._last_prefix_ae = { "loss": float(ae.detach()), "tok_acc": float(tok_acc.detach()) if torch.is_tensor(tok_acc) else float(tok_acc), "key_acc": float(key_acc.detach()) if torch.is_tensor(key_acc) else float(key_acc), "n": int(n), } w = float(cfg.message_prefix_ae_weight) if w == 0: return loss return loss + ae * k_bar.new_tensor(w) def _get_flce(self): if self._flce is None: cls = _liger_flce() if cls is None: self.config.use_liger = False return None self._flce = cls( ignore_index=-100, reduction="sum", softcap=self.config.logit_softcap or None, lse_square_scale=self.config.z_loss, ) return self._flce # -- family hooks --------------------------------------------------------------- @torch.no_grad() def prefix_kv(self, input_ids, attention_mask=None, doc_ids=None, as_message: bool = False): """K/V of the global read layer for `input_ids` β€” the one-layer prefix cache and the message object for E19/E21. Returns (k, v) each [B,S,g,dh] (RoPE applied to k). `as_message=True` (E21) returns the **compressed message** instead: (kΜ„, vΜ„, slot_pos) with one slot per `message_compress_ratio` tokens. Default is complete blocks only (⌊S/rβŒ‹ slots β€” exactly the slots a receiver of the concatenated row would be allowed to read). `message_pool_remainder` also keeps the last incomplete block. Feed it to `forward(receiver_ids, message_kv=..., position_offset=S)`. """ cfg = self.config if str(getattr(cfg, "lm_note_key", "writer")) == "tied" or str(getattr(cfg, "par_global_read", "dense")) == "lsa": raise NotImplementedError("prefix_kv is not defined for the E33p reads (tied notes, LSA)") if cfg.par_mode == "perceiver" and cfg.global_layers < 1: raise RuntimeError("prefix_kv needs a global read layer") gi = cfg.global_layer_index input_ids, attention_mask, _, doc_ids, S = self._pad_inputs(input_ids, attention_mask, None, doc_ids) x_in = self._run_layers(input_ids, attention_mask, doc_ids, None, capture_input_of=gi) layer = self.layers[gi] h = layer.attn_norm(x_in) pos = self._positions(input_ids.shape[1], input_ids.shape[0], doc_ids, input_ids.device) if as_message: if self.memory_writer is not None: raise NotImplementedError("prefix_kv(as_message=True) is not wired for latent_memory (E31)") if layer.attn.compressor is None: raise RuntimeError("as_message needs message_boundary_token_id >= 0") k_raw, v = layer.attn.kv_raw(h, input_ids) k_bar, v_bar = layer.attn.compressor(h, k_raw, v, layer.attn.k_norm) if str(getattr(cfg, "message_write", "block_mean") or "block_mean") == "sw_perceiver": slot_pos = layer.attn.compressor.slot_positions(pos[:, :S]) k_bar, v_bar = k_bar[:, : slot_pos.shape[1]], v_bar[:, : slot_pos.shape[1]] else: r = cfg.message_compress_ratio n_keep = -(-S // r) if cfg.message_pool_remainder else S // r k_bar, v_bar = k_bar[:, :n_keep], v_bar[:, :n_keep] end_idx = (torch.arange(n_keep, device=input_ids.device) * r + (r - 1)).clamp(max=max(S - 1, 0)) slot_pos = pos[:, end_idx] if layer.attn.use_rope: cos_s, sin_s = rope_cos_sin(slot_pos, cfg.head_dim, cfg.rope_theta, k_bar.dtype) k_bar = apply_rope(k_bar, cos_s, sin_s) return k_bar, v_bar, slot_pos k, v = layer.attn.kv(h, input_ids) cos, sin = rope_cos_sin(pos, cfg.head_dim, cfg.rope_theta, k.dtype) if layer.attn.use_rope: k = apply_rope(k, cos, sin) return k[:, :S], v[:, :S] @torch.no_grad() def generate(self, input_ids, max_new_tokens=32, temperature=0.0, top_k=0, eos_token_id=None): """v1 sampler without KV cache (full recompute per step) β€” for probes only.""" self.eval() out = input_ids for _ in range(max_new_tokens): logits = self(out).logits[:, -1] if temperature <= 0: nxt = logits.argmax(-1, keepdim=True) else: logits = logits / temperature if top_k: kth = torch.topk(logits, top_k).values[:, -1:] logits = logits.masked_fill(logits < kth, float("-inf")) nxt = torch.multinomial(F.softmax(logits, -1), 1) out = torch.cat([out, nxt], dim=1) if eos_token_id is not None and bool((nxt == eos_token_id).all()): break return out # -------------------------------------------------------------------------------------- # Parameter accounting (used by tests and run reports) # -------------------------------------------------------------------------------------- @dataclass class ParamBreakdown: dense: int sparse_tables: int @property def total(self) -> int: return self.dense + self.sparse_tables def _swp_param_count(cfg: PerceiverARConfig) -> int: """Learned query bank + scoring projection (E30). Independent of seq_len.""" d = cfg.hidden_size bank = max(1, int(getattr(cfg, "swp_bank_size", SWP_BANK_DEFAULT) or SWP_BANK_DEFAULT)) coverage = max(1, int(getattr(cfg, "swp_coverage", SWP_COVERAGE_DEFAULT) or SWP_COVERAGE_DEFAULT)) n_heads, qdim = swp_resolved_heads(cfg) dh_q = qdim // n_heads max_w = max(bank * coverage, int(getattr(cfg, "swp_window", 0) or 0), 1) return ( d # RMSNorm on h + bank * n_heads * dh_q # q + d * n_heads * dh_q # wk + dh_q + dh_q # q_norm, k_norm_q + max_w * n_heads # pos_bias ) def analytic_param_count(cfg: PerceiverARConfig) -> ParamBreakdown: d, ff, e, V = cfg.hidden_size, cfg.intermediate_size, cfg.token_embedding_dim, cfg.vocab_size h, g, dh = cfg.num_attention_heads, cfg.num_kv_heads, cfg.head_dim L = cfg.total_layers per_layer = (d * h * dh) + 2 * (d * g * dh) + (h * dh * d) + 3 * d * ff + 2 * d + 2 * dh + 2 dense = L * per_layer + (L // 2) # + one Οƒ per skip-consuming layer dense += V * e + 2 * e * d + d * d + d # tok table + up0/up1/up2 + norm dense += d + (d * e if getattr(cfg, "lm_head_tied", False) else d * V) # final norm + head (tied: projection) if cfg.write_back_hook: dense += d * 2 * g * dh if getattr(cfg, "global_logit_scale", "none") == "log": dense += sum(1 for pat, _ in cfg.layer_patterns() if pat == "full") # one scalar per full layer if getattr(cfg, "message_enabled", False): n_full = sum(1 for pat, _ in cfg.layer_patterns() if pat == "full") write = str(getattr(cfg, "message_write", "block_mean") or "block_mean") if write == "sw_perceiver": dense += n_full * _swp_param_count(cfg) elif write == "latent_memory": with torch.device("meta"): dense += sum(p.numel() for p in LatentMemoryWriter(cfg).parameters()) else: dense += n_full * (g * d + d * 2 * g * dh) # KVCompressor: u + delta if int(getattr(cfg, "message_loop_rounds", 1) or 1) > 1 and getattr(cfg, "message_loop_control", "none") != "none": dense += loop_control_param_count(cfg) # E33c: the loop's question control sparse = len(cfg.ngram_orders) * cfg.ngram_buckets * e n_ve = sum(1 for i in range(L) if i in cfg.value_embed_layers) sparse += n_ve * (V * cfg.value_embed_dim) dense += n_ve * (cfg.value_embed_dim * g * dh + 1) return ParamBreakdown(dense=dense, sparse_tables=sparse) # ============================================================================================================== # nn/incremental.py # ============================================================================================================== # Cached greedy decoding for the Perceiver AR family (`nn/perceiver_ar_lm.py`): the row is read once, then each step # runs only the new position through the layers (2026-11-12). # # Why. The harness decoding (`evaluation/lm_eval_perceiver_ar.PerceiverARLMEval._model_generate`) re-runs the whole row # for every answer token. E33t stage D measured 5.2 s per forward at 64k for the catalogue model on one L40S and 32 # forwards per RULER prompt (180 s a prompt, ~16 h for the 13 tasks at 25 prompts each). Here the row is read once (the # prefill: the model's own forward over the same fixed-length row), while every attention call's keys and values are # kept; a step then costs one position through every layer, reading the cached keys. # # Exactness. The row geometry is the uncached decoding's: one row of `Lb` tokens for the whole answer, the slots after # the current position written as eos with document id βˆ’1. A position's output depends only on earlier positions # (tests/test_note_open.py::test_no_future_leak, tests/test_lsa_read.py::test_lsa_no_future_leak), so the prefill's keys # of the prompt are the uncached decoding's at every step, and each step writes its own position's keys. What the # reading layer derives from many keys is rebuilt when it could change for the current query: # # * LSA's read (E33p): the buckets of a closed 512-key block are visible to later blocks. When the decoding reaches a # block end and that block holds answer tokens, every pass's buckets are rebuilt from the cache (`lsa_groups`). # * The catalogue read (E33t): the notes only choose what opens, and a note opens only members older than the raw # window. A page holding answer tokens starts after L0 βˆ’ lm_window, so it has no member that old while the answer is # shorter than raw_window βˆ’ lm_window (256 tokens for E33t n4): the prefill's notes are exact for such answers (with # the cosine score, which does not depend on the other visible notes), and a longer request is refused up front. # * E37's concept read (2026-11-13): concepts of a closed 512-key block are visible two blocks later, and with the # reasoner the block before the query's own reads the reasoned update. When the decoding reaches a block end and that # block holds answer tokens, every pass's concepts and updates are rebuilt from the cache (`build_concepts`). # * E33p's notes read (notes_open, 2026-11-13): the notes are keys of the read (values from the writer, tied keys from # the reading layer's keys), and a page closes at its last written token. So a page holding the newest position is # rewritten every step: the writer runs again on that page (it reads page text only, each page on its own) and its # tied keys are redone per pass. Such a page is visible to the newest position only: when the next token is written, # the page closes one position later and the previous position no longer reads it, so each step first redoes the # previous position (two positions per step). Answers stay shorter than raw_window βˆ’ lm_window, as for the catalogue. # # The reading layer reads through the list read (`attend_list`, `ChoiceList`), which gives the table read's outputs # (tests/test_catalogue_read.py::test_list_read_matches_table, tests/test_lsa_read.py::test_lsa_list_read_matches_table), # or, for the concept and notes reads, one query's row of the table (the same `choose`) and one fp32 softmax. # The tokens equal the uncached decoding's and the logits agree to float rounding (tests/test_incremental_decode.py). # # Read once, answer many (2026-11-14). `snapshot()` after a prefill is the cache of that row; `ask(snap, question, # new)` restores it, writes the question's tokens as steps (one position each, like answer tokens) and decodes greedily. # A document is then read once and every question costs only its own tokens and its answer's, with the tokens a fresh # prefill over document + question would write (tests/test_incremental_decode.py::test_read_once_answer_many). For the # catalogue and notes reads the question and the answer together stay under `max_new_tokens()`. # The snapshot is a full copy of the state (about 0.3 GB at 64k for a 100M model, ~1 ms on the GPU). Follow-ups if many # snapshots are ever held at once (review by the cache's author, 2026-11-14): let the snapshot and the live state share # K / V / X up to t0 βˆ’ 2 and clone only the tails, restoring with copy_ β€” the tail must start at t0 βˆ’ 1, because the # notes read redoes position t0 βˆ’ 1 on its first step and rewrites the pages holding t0 βˆ’ 1 and t0, whose page tensors # need full copies; and add a test that no two state tensors share storage (`_clone_state` keeps aliasing by object # identity, so a view stored next to its base and written in place would be split; nothing does that today). # # Supported; anything else raises NotImplementedError before any work, so callers keep the uncached path: perceiver # par_mode, causal, no message boundary, one global layer, the tied loop over [global read + span layers] with loop # markers (and the prelude gate), sliding-window local layers without sinks; the reading layer is full attention, # LSA's read, E37's concept read (with or without the reasoner and the length scale), the catalogue read (index notes # on non-overlapping pages, cosine score, no pass exclusion, one level), or E33p's notes read (tied keys, notes or # nothing opened, argmax filing, the writer reading the token table). Not yet: page-level opening, note-age or count # heads, write-back hooks, loop control, loop feedback. def lsa_groups(*args, **kwargs): # nn/lsa_buckets.py is not part of this export raise NotImplementedError("lsa_groups: this checkpoint's config does not use nn/lsa_buckets.py") def lsa_open_table(*args, **kwargs): # nn/lsa_buckets.py is not part of this export raise NotImplementedError("lsa_open_table: this checkpoint's config does not use nn/lsa_buckets.py") def _clone_state(x, memo: Optional[dict] = None): """A copy of a decoder state: every tensor cloned once (two names of one tensor stay one tensor), containers and plain objects rebuilt, modules and functions shared.""" memo = {} if memo is None else memo if id(x) in memo: return memo[id(x)] if x is None or isinstance(x, (bool, int, float, str, bytes, torch.nn.Module, type)) or callable(x): return x if torch.is_tensor(x): y = x.detach().clone() elif isinstance(x, dict): y = {} memo[id(x)] = y for k, v in x.items(): y[k] = _clone_state(v, memo) return y elif isinstance(x, list): y = [] memo[id(x)] = y y.extend(_clone_state(v, memo) for v in x) return y elif isinstance(x, tuple): vals = [_clone_state(v, memo) for v in x] y = type(x)(*vals) if hasattr(x, "_fields") else tuple(vals) elif hasattr(x, "__dict__"): y = copy.copy(x) memo[id(x)] = y for k, v in vars(x).items(): object.__setattr__(y, k, _clone_state(v, memo)) return y else: y = copy.deepcopy(x) memo[id(x)] = y return y def _refuse(why: str): raise NotImplementedError(f"cached decoding: {why}") def decode_kind(model: PerceiverARLM) -> str: """'dense' | 'lsa' | 'catalogue': the reading layer the cached decoding reproduces; NotImplementedError otherwise.""" cfg, m = model.config, model if cfg.par_mode != "perceiver": _refuse("par_mode must be 'perceiver'") if cfg.block_attention_mode != "causal": _refuse("causal blocks only") if int(cfg.message_boundary_token_id) >= 0: _refuse("rows with a message boundary") if int(cfg.global_layers) != 1: _refuse("one global layer") if m.loop_control is not None or m.loop_feedback_gate is not None: _refuse("loop control / loop feedback") if m._loop_rounds_override: _refuse("a loop-round override") if bool(getattr(cfg, "write_back_hook", False)) or bool(getattr(cfg, "swa_sink", False)): _refuse("write-back hook / swa sinks") if any(b.read_rounds != 1 for b in m.layers): _refuse("read rounds inside a block") if m._notes_override is not None or m._note_keep is not None or m._note_capture is not None: _refuse("a notes probe is armed") gi = cfg.global_layer_index for i, b in enumerate(m.layers): if b.flow is not None or b.attn.flow is not None: _refuse("flow instrumentation is armed") if i != gi and b.attn.pattern != "swa": _refuse("local layers must be sliding-window") att = m.layers[gi].attn if att.pattern != "full": _refuse("the global layer is not a full read") if att.concept is not None: if m.memory_writer is not None or att.compressor is not None: _refuse("the concept read with a notebook or a compressor") if att.concept_stats is not None: _refuse("a concept-read probe is armed") return "concept" if att.lsa is not None: if m.memory_writer is not None: _refuse("LSA's read with a notebook writer") return "lsa" if m.memory_writer is None: if att.compressor is not None: _refuse("a compressed-message read") return "dense" if str(getattr(cfg, "lm_read", "exclusive")) != "closed": _refuse("latent memory without the closed read") if str(getattr(cfg, "lm_note_key", "writer")) != "tied": _refuse("E31's writer-keyed notes (only tied note keys: E33p's notes read, E33t's catalogue)") if int(getattr(cfg, "message_extra_slot_attends", 0) or 0) or bool(getattr(cfg, "message_update_slot_kv", False)): _refuse("extra slot reads") if att.note_age_slope is not None or att.note_counter is not None: _refuse("note-age / count heads") if int(getattr(cfg, "message_raw_window", 0) or 0) <= 0: _refuse("notes without a raw window") note_read = str(getattr(cfg, "lm_note_read", "gist")) if note_read == "gist": # E33p: the notes are keys of the read (values from the writer) and the index if str(cfg.lm_open) not in ("notes", "none") or int(getattr(cfg, "lm_open_levels", 1) or 1) != 1: _refuse("the notes read: notes (or nothing) open, one level") if bool(getattr(cfg, "lm_open_new_per_pass", False)): _refuse("the notes read with pass exclusion") if str(getattr(cfg, "lm_filing", "argmax")) != "argmax": _refuse("the notes read with balanced filing") if str(getattr(cfg, "lm_writer_input", "table")) != "table": _refuse("a writer that reads the decoder's input layer (lm_writer_input='embed')") if m._open_eval != "on" or m._message_override != "real": _refuse(f"eval switches (open {m._open_eval!r}, message {m._message_override!r})") return "notes" if note_read != "index": _refuse(f"lm_note_read {note_read!r}") if str(cfg.lm_open) not in ("notes", "none") or int(getattr(cfg, "lm_open_levels", 1) or 1) != 1: _refuse("catalogue: notes (or nothing) open, one level") if bool(getattr(cfg, "lm_open_new_per_pass", False)) and m._open_eval != "reuse": _refuse("catalogue with pass exclusion") if int(cfg.lm_window) != int(cfg.lm_stride): _refuse("catalogue on overlapping pages") if str(getattr(cfg, "lm_open_score", "sum_softmax")) != "max_cos": # a softmax over the visible notes would count the pages holding answer tokens, which the prefill's # notebook does not have; the cosine score of a note does not depend on the others _refuse("catalogue scored by a softmax over the visible notes") if m._message_override not in ("real", "none"): _refuse(f"message override {m._message_override!r}") return "catalogue" @dataclass class _Catalogue: ni: object # nn.exact_read.NoteOpen of the prefill slot_close: torch.Tensor slot_doc: torch.Tensor doc: torch.Tensor # the message context's doc [B, S], answer positions written as they come tag: torch.Tensor # its (doc, side) tags [B, S] int32 tag_stride: int rw: int open: bool kappa: list # per loop pass: tied note keys [B, C, 1, dh] in the keys' dtype members: Optional[torch.Tensor] ek: Optional[torch.Tensor] # learned empty slots [n, g, dh] ev: Optional[torch.Tensor] class IncrementalDecoder: """Prefill once, then one position per step. `greedy` is the drop-in for the uncached harness loop.""" def __init__(self, model: PerceiverARLM): self.m = model self.cfg = model.config self.kind = decode_kind(model) self.gi = self.cfg.global_layer_index # ------------------------------------------------------------------ limits def max_new_tokens(self) -> Optional[int]: """Longest answer the cached state stays exact for (None = any).""" if self.kind in ("catalogue", "notes"): # a page holding answer tokens has no member old enough to open return int(self.cfg.message_raw_window) - int(self.cfg.lm_window) return None # ------------------------------------------------------------------ prefill @torch.no_grad() def prefill(self, buf: torch.Tensor, doc: torch.Tensor, L0: int, all_positions: bool = False) -> torch.Tensor: """buf [B, Lb]: the prompt in [0, L0), anything after; doc [B, Lb]: document ids, βˆ’1 = padding or not yet written. Runs the model's forward over the row and keeps every attention call's keys and values. Returns the final-norm hidden state at L0 βˆ’ 1 [B, d] (`all_positions`: of every prompt position [B, L0, d]).""" m, cfg = self.m, self.cfg mult = int(cfg.attn_pad_multiple) S0 = buf.shape[1] if mult > 1 and S0 % mult: # the forward's own right padding (`_pad_inputs`), done once here pad = mult - S0 % mult buf = F.pad(buf, (0, pad), value=int(cfg.pad_token_id)) doc = F.pad(doc, (0, pad), value=-1) self.buf, self.doc = buf.clone(), doc.clone().long() self.B, self.S = buf.shape self.L0, self.t = int(L0), int(L0) calls: list = [] msgs: dict = {} gatt = m.layers[self.gi].attn keep_x = self.kind == "concept" and gatt.concept_reasoner is not None # the reasoner reads the layer input def hook(mod, args, kwargs): x = args[0] k_raw, v = mod.kv_raw(x, kwargs.get("ids")) k = mod.k_norm(k_raw) if mod.use_rope: k = apply_rope(k, kwargs["cos"], kwargs["sin"]) calls.append((mod.layer_idx, k, v, x if (keep_x and mod.layer_idx == self.gi) else None)) if kwargs.get("message") is not None: msgs[mod.layer_idx] = kwargs["message"] handles = [b.attn.register_forward_pre_hook(hook, with_kwargs=True) for b in m.layers] try: h = m.hidden_states(self.buf, doc_ids=self.doc) finally: for hd in handles: hd.remove() self.K: dict = {} self.V: dict = {} self.X: dict = {} # the reading layer's input per pass (the concept reasoner's states) seen: dict = {} for li, k, v, x in calls: r = seen.get(li, 0) seen[li] = r + 1 self.K[(li, r)], self.V[(li, r)] = k, v if x is not None: self.X[(li, r)] = x.clone() self.passes = seen.get(self.gi, 1) self._ds0 = doc_starts(self.doc) # document starts of the prompt (answer slots are added per step) self._ds_cols: dict = {} if self.kind == "lsa": self._build_lsa() elif self.kind == "concept": self._build_concepts() elif self.kind == "catalogue": self._build_catalogue(msgs.get(self.gi)) if self.cat.open: self.cat.ni.groups.doc_start = self.cat.ni.groups.doc_start.clone() elif self.kind == "notes": self._build_notes(msgs.get(self.gi)) return h[:, :self.L0] if all_positions else h[:, self.L0 - 1] def _ds_col(self, j: int) -> torch.Tensor: """[B] document start of position j (prompt: from the prefill; answer slots: as written).""" return self._ds_cols[j] if j in self._ds_cols else self._ds0[:, j] def _build_lsa(self) -> None: c = self.m.layers[self.gi].attn.lsa self.lsa_groups = [] for r in range(self.passes): built = lsa_groups(self.K[(self.gi, r)], self.doc, block=c["block"], per_block=c["per_block"], pool=c["pool"], cap=c["cap"], sinks=c["sinks"]) if built is None: self.lsa_groups.append(None) continue centroids, gidx = built members = ChoiceList(gidx, self.B, 1, cap=c["top_k"], m=1).members() self.lsa_groups.append((centroids, gidx, members)) def _build_concepts(self) -> None: """E37: each pass's concepts of the written row (nn.concept_memory.build_concepts, as `_concept_read`), the reasoner's value updates, per concept and spread to the member tokens.""" pass # nn.concept_memory: in this file att = self.m.layers[self.gi].attn c = att.concept doc = self.doc ds = doc_starts(doc) pos = torch.arange(self.S, device=doc.device)[None] sink = (pos - ds < int(c["sinks"])) & (doc >= 0) self.cc = [] for r in range(self.passes): if att.concept_off: self.cc.append(None) continue x = self.X[(self.gi, r)] if att.concept_reasoner is not None else None cidx = build_concepts(self.K[(self.gi, r)], self.V[(self.gi, r)], x, doc, sink, block=int(c["block"]), per_block=int(c["per_block"]), iters=int(c["iters"]), tau=float(c["tau"])) if cidx is None: self.cc.append(None) continue dv = dv_tok = None if att.concept_reasoner is not None: dv = att.concept_reasoner(cidx.z, cidx.block_of, cidx.c_doc) dv_tok = token_update(cidx, dv, self.S) self.cc.append((cidx, dv, dv_tok)) def _build_notes(self, msg) -> None: """E33p's notes read: the prefill's notebook (the writer's note values, the tied keys' assignment, when each page closed), copied so the pages holding answer tokens can be rewritten as the answer grows.""" if msg is None or msg.index is None or msg.slots is None: raise RuntimeError("the notes prefill built no notebook") ni = msg.index geo = self.m.memory_writer.geometry(self.S) k0 = self.K[(self.gi, 0)] self.nt = SimpleNamespace( ni=ni, W=int(geo.window), K=int(geo.latents), starts=list(geo.starts), rw=int(msg.raw_window or 0), v_bar=msg.slots[1].clone(), assign=ni.assign.clone(), slot_close=msg.slot_close.clone(), slot_doc=msg.slot_doc.clone(), open=ni.mode != "none", kappa=[tied_note_keys(ni.assign, self.K[(self.gi, r)], ni.page_tok).to(k0.dtype) for r in range(self.passes)], dirty=[], ) if self.nt.open: ni.groups.doc_start = ni.groups.doc_start.clone() def _rewrite_pages(self, t: int) -> None: """The pages holding position t gained a token: their notes again from the writer (it reads page text only, each page on its own), as the uncached forward writes them for this row. Their tied keys are redone per pass once the pass has written its key at t (`_notes_read`).""" m, st = self.m, self.nt W, K = st.W, st.K wins = [w for w, s in enumerate(st.starts) if s <= t < s + W] pos = m._positions(self.S, self.B, self.doc, self.buf.device) for w in wins: s = st.starts[w] ids, doc = self.buf[:, s:s + W], self.doc[:, s:s + W] out = m.memory_writer(m._writer_input(ids, doc), torch.zeros_like(doc), doc, None, pos[:, s:s + W], self.cfg.rope_theta) st.assign[:, w] = out["assign"].float().mean(1).reshape(self.B, K, W) st.v_bar[:, w * K:(w + 1) * K] = out["v"].to(st.v_bar.dtype) st.slot_doc[:, w * K:(w + 1) * K] = out["slot_doc"] tok = s + torch.arange(W, device=doc.device) last = torch.where(out["window_pick"][:, 0], tok[None], torch.full_like(doc, -1)).amax(-1) st.slot_close[:, w * K:(w + 1) * K] = last[:, None] # tied keys to redo per pass: pages holding t, and those holding t βˆ’ 1 (its keys are redone this step) st.dirty = [w for w, s in enumerate(st.starts) if s <= t < s + W or s <= t - 1 < s + W] def _build_catalogue(self, msg) -> None: att = self.m.layers[self.gi].attn if msg is None or msg.index is None: raise RuntimeError("the catalogue prefill built no note index") ni = msg.index tag, _ = msg.tags() k0 = self.K[(self.gi, 0)] open_ = ni.mode != "none" and msg.override == "real" and getattr(msg, "open_eval", "on") != "off" ek = ev = None if att.sink_k is not None and int(att.sink_k.shape[0]) > 0: n, g, dh = int(att.sink_k.shape[0]), att.g, att.dh ek = att.k_norm(att.sink_k).to(k0.dtype)[:, None, :].expand(n, g, dh) ev = att.sink_v.to(self.V[(self.gi, 0)].dtype)[:, None, :].expand(n, g, att.sink_v.shape[-1]) self.cat = _Catalogue( ni=ni, slot_close=msg.slot_close, slot_doc=msg.slot_doc, doc=msg.doc.clone(), tag=tag.clone(), tag_stride=int(msg.tag_stride()), rw=int(msg.raw_window or 0), open=bool(open_), kappa=[tied_note_keys(ni.assign, self.K[(self.gi, r)], ni.page_tok).to(k0.dtype) for r in range(self.passes)], members=(ChoiceList(ni.groups, self.B, 1, cap=ni.cap, m=1).members() if open_ else None), ek=ek, ev=ev, ) # ------------------------------------------------------------------ one step @torch.no_grad() def step(self, tok: torch.Tensor) -> torch.Tensor: """Write `tok` [B] at the next position and return that position's final-norm hidden state [B, d].""" m, cfg = self.m, self.cfg t = self.t if t >= self.S: raise RuntimeError("the row is full") B = self.B # A block holding answer tokens just closed: rebuild what the reading layer derives from the closed blocks, # from the tokens written so far (position t is still unwritten; its own block is not read this way) if self.kind in ("lsa", "concept") and t > self.L0: att = m.layers[self.gi].attn blk = int((att.lsa if self.kind == "lsa" else att.concept)["block"]) if t % blk == 0: self._build_lsa() if self.kind == "lsa" else self._build_concepts() self.buf[:, t] = tok self.doc[:, t] = 0 # as the uncached decoding: every written answer slot is document 0 # where the new position's document starts: its queries count the opened members from there # (`choose`, `ChoiceList.opened`); the prefill's indexes saw this slot as padding prev = self.doc[:, t - 1] if t else torch.full_like(self.doc[:, 0], -2) ds_t = torch.where(prev == self.doc[:, t], self._ds_col(t - 1), torch.full_like(prev, t)) self._ds_cols[t] = ds_t if self.kind == "catalogue": self.cat.doc[:, t] = 0 self.cat.tag[:, t] = 0 if self.cat.open: self.cat.ni.groups.doc_start[:, t] = ds_t elif self.kind == "lsa": for built in self.lsa_groups: if built is not None: built[1].doc_start[:, t] = ds_t elif self.kind == "concept": for built in self.cc: if built is not None: built[0].groups.doc_start[:, t] = ds_t elif self.kind == "notes": if self.nt.open: self.nt.ni.groups.doc_start[:, t] = ds_t self._rewrite_pages(t) if t: # The pages holding t βˆ’ 1 and t closed at t βˆ’ 1 in the last row, so t βˆ’ 1 read their notes; with t # written they close at t and t βˆ’ 1 no longer reads them. The uncached forward over this row computes # t βˆ’ 1 that way, and t reads its keys: redo t βˆ’ 1 first (its output is not used). self._position(t - 1) h = self._position(t) self.t = t + 1 return h def _position(self, t: int) -> torch.Tensor: """Run position t (already written) through the layers with the cached keys of the earlier positions, writing its own keys and values; its final-norm hidden state [B, d].""" m, cfg = self.m, self.cfg B = self.B dev = self.buf.device orders = tuple(int(o) for o in (cfg.ngram_orders or ())) lo = max(0, t - (max(orders) if orders else 1) + 1) x0 = m.embed(self.buf[:, lo:t + 1], self.doc[:, lo:t + 1])[:, -1:] pos = m._positions(t + 1, B, self.doc[:, :t + 1], dev)[:, t:t + 1] cos, sin = rope_cos_sin(pos, cfg.head_dim, cfg.rope_theta, x0.dtype) ids = self.buf[:, t:t + 1] self._ds = doc_starts(self.doc) if self.kind in ("lsa", "concept") else None n = len(m.layers) n_skip = n // 2 def run(i, x, skips, r): layer = m.layers[i] skip = skips.pop() if (i >= n - n_skip and skips) else None x = layer.mix(x, x0, skip) x = x + self._attn(i, r, layer.attn, layer.attn_norm(x), ids, cos, sin, pos, t) x = x + layer.mlp(layer.mlp_norm(x)) if i < n_skip: skips.append(x) return x x, skips = x0, [] if m.loop_emb is not None: core = range(self.gi, self.gi + 1 + int(cfg.message_loop_span)) for i in range(self.gi): x = run(i, x, skips, 0) prelude, skips0 = x, list(skips) s = skips0 for r in range(int(m.loop_rounds)): x = x + m.loop_emb[min(r, m.loop_emb.shape[0] - 1)].to(x.dtype) if r and m.loop_gate is not None: x = x + m.loop_gate.to(x.dtype) * prelude s = list(skips0) for i in core: x = run(i, x, s, r) skips = s for i in range(core.stop, n): x = run(i, x, skips, 0) else: for i in range(n): x = run(i, x, skips, 0) return m.final_norm(x)[:, 0] def _attn(self, i, r, att, h, ids, cos, sin, pos, t): B = h.shape[0] q = att.q_norm(att.wq(h).view(B, 1, att.h, att.dh)) k_raw, v = att.kv_raw(h, ids) k = att.k_norm(k_raw) if att.use_rope: q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) q = att._scale_q(q, pos) K, V = self.K[(i, r)], self.V[(i, r)] K[:, t] = k[:, 0] V[:, t] = v[:, 0] if (i, r) in self.X: self.X[(i, r)][:, t] = h[:, 0] if att.pattern == "swa": o = self._window_read(q, K, V, t, int(att.window)) elif self.kind == "dense": o = self._window_read(q, K, V, t, t + 1) elif self.kind == "lsa": o = self._lsa_read(q, K, V, r, t, att) elif self.kind == "concept": o = self._concept_read(q, K, V, r, t, att) elif self.kind == "notes": o = self._notes_read(q, K, V, r, t) else: o = self._catalogue_read(q, K, V, r, t) return att.wo(o.reshape(B, 1, att.h * att.dh)) def _window_read(self, q, K, V, t, w): """Keys [t βˆ’ w + 1, t] of the query's document (make_mask_pred: causal, window, same document).""" lo = max(0, t - w + 1) k, v = K[:, lo:t + 1], V[:, lo:t + 1] ok = self.doc[:, lo:t + 1] == self.doc[:, t:t + 1] # [B, L] h, g = q.shape[2], k.shape[2] qt, kt, vt = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if g != h: kt = kt.repeat_interleave(h // g, dim=1) vt = vt.repeat_interleave(h // g, dim=1) o = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=ok[:, None, None, :]) return o.transpose(1, 2) def _lsa_read(self, q, K, V, r, t, att): c = att.lsa opened = None built = self.lsa_groups[r] if not att.lsa_off and built is not None: centroids, gidx, members = built opened = lsa_open_table(q, centroids, gidx, top_k=c["top_k"], width=c["width"], raw_window=c["window"], impl="list", q_offset=t, members=members) return attend_list(q, K, V, opened=opened, raw_window=c["window"], tag=self.doc, key_valid=None, ds=self._ds, n_sinks=c["sinks"], valid_query=True, q_offset=t) def _concept_read(self, q, K, V, r, t, att): """E37 (nn.concept_memory.attend_concepts) for the query t: one softmax over its document's sinks, the block-aligned window (its block and the one before), the member tokens of the concepts it opens (largest estimated mass first, until top_k tokens) and one summary entry per other visible concept, with the summaries' bias log n + |q|Β² σ² / 2d (+ log ρ, the length scale). With the reasoner, keys before the query's block read v + the update, its own block the raw v (attend_concepts' two copies; their masks do not overlap). fp32.""" pass # nn.concept_memory: in this file c = att.concept blk, cap = int(c["block"]), int(c["top_k"]) B, _, h, d = q.shape n = t + 1 jpos = torch.arange(n, device=q.device) doc, doc_t, ds = self.doc[:, :n], self.doc[:, t], self._ds own_lo = (t // blk) * blk sink = ((jpos[None] - ds[:, :n]) < int(c["sinks"])) & (doc >= 0) keep = (jpos >= own_lo - blk)[None] | sink vt = V[:, :n] ks, vs, sbias = None, None, None built = self.cc[r] if built is not None: cidx, dv, dv_tok = built gi = cidx.groups G = gi.n_groups score = summary_logit(q, cidx, variance=bool(c["variance"])).amax(2) # [B, 1, C] visible = (gi.g_close[:, None, :] <= t) & torch.isfinite(score) ids, off = choose(torch.nan_to_num(score, neginf=-1e30), visible, gi, torch.tensor([t], device=q.device), m=int(c["width"]), cap=cap, raw_window=blk) row = torch.full((B, G), cap, dtype=torch.int32, device=q.device) # the table's row of t row.scatter_(1, ids[:, 0], off[:, 0].to(torch.int32)) codes = gi.codes[0, :, :n].long() g = torch.div(codes, ORD_MOD, rounding_mode="floor") hit = (codes >= 0) & (row.gather(1, g.clamp(0, G - 1)) + (codes - g * ORD_MOD) < cap) keep = keep | (hit & ((t - jpos) >= blk)[None]) if dv_tok is not None: vt = torch.where((jpos < own_lo)[None, :, None, None], vt + dv_tok[:, :n].to(vt.dtype), vt) if c["summaries"]: C = cidx.n_concepts vis = ((t >= (cidx.block_of + 2) * blk)[None] & (cidx.c_doc == doc_t[:, None]) & (doc_t >= 0)[:, None] & ~(row[:, :C] < cap)) # [B, C] logn = torch.where(cidx.n > 0, cidx.n.clamp_min(1.0).log(), torch.zeros_like(cidx.n)) vhalf = 0.5 * cidx.var if c["variance"] else torch.zeros_like(cidx.var) qn2 = (q.float() ** 2).sum(-1)[:, 0] / d # [B, h] sb = logn[:, None, :].float() + qn2[..., None] * vhalf[:, None, :].float() # [B, h, C] lr = summary_log_scale(ds[:, :n], n, blk, int(c.get("sum_len", 0) or 0)) if lr is not None: sb = sb + lr[:, t][:, None, None] sbias = sb.masked_fill(~vis[:, None, :], float("-inf")) ks = cidx.mu_k[:, :, None].to(K.dtype) vs = (cidx.mu_v if dv is None else cidx.mu_v + dv.to(cidx.mu_v.dtype))[:, :, None].to(V.dtype) mask = keep & (doc == doc_t[:, None]) & (doc_t >= 0)[:, None] # [B, n] kk, vv = K[:, :n, 0].float(), vt[:, :, 0].float() # one key head bias = torch.zeros(B, n, device=q.device).masked_fill(~mask, float("-inf"))[:, None].expand(B, h, n) if sbias is not None: kk = torch.cat([kk, ks[:, :, 0].float()], 1) vv = torch.cat([vv, vs[:, :, 0].float()], 1) bias = torch.cat([bias, sbias], -1) lg = torch.einsum("bhd,bkd->bhk", q[:, 0].float(), kk) / math.sqrt(d) + bias o = torch.einsum("bhk,bkd->bhd", torch.softmax(lg, -1), vv) return o[:, None].to(q.dtype) def _notes_read(self, q, K, V, r, t): """E33p (`_attend_open` with the closed rule) for the query t: one softmax over its document's raw window, the raw tokens of the notes it opens (nn.exact_read.note_open_table: its k best visible notes holding a member older than the window, oldest members first, up to cap tokens) and every note of its document whose page closed at or before t (keys: the tied keys of this pass, values: the writer's). fp32.""" st = self.nt ni = st.ni Kn = st.K for w in st.dirty: # pages holding t βˆ’ 1 or t: tied keys with this pass's latest keys there st.kappa[r][:, w * Kn:(w + 1) * Kn] = tied_note_keys(st.assign[:, w:w + 1], K, ni.page_tok[w:w + 1]).to(st.kappa[r].dtype) B, _, h, dh = q.shape g = K.shape[2] n = t + 1 jpos = torch.arange(n, device=q.device) doc_t = self.doc[:, t] same = (self.doc[:, :n] == doc_t[:, None]) & (doc_t >= 0)[:, None] # one side per row raw = same & ((t - jpos) < st.rw)[None] kap = st.kappa[r] # [B, C, g, dh] vis = ((st.slot_doc >= 0) & (st.slot_close >= 0) & (st.slot_doc == doc_t[:, None]) & (doc_t >= 0)[:, None] & (st.slot_close <= t)) # [B, C] qf = q[:, 0].float() # [B, h, dh] rep = h // g if st.open: gi = ni.groups G, cap = gi.n_groups, int(ni.cap) kb = kap[:, :, 0].float() if ni.score == "max_cos": s_note = torch.einsum("bhd,bcd->bhc", F.normalize(qf, dim=-1), F.normalize(kb, dim=-1)).amax(1) else: lg = torch.einsum("bhd,bcd->bhc", qf, kb) * dh ** -0.5 p = torch.softmax(lg.masked_fill(~vis[:, None], float("-inf")), dim=-1) s_note = torch.nan_to_num(p, nan=0.0).sum(1) # [B, C] cand = vis & (gi.g_minpos <= t - st.rw) ids, off = choose(s_note[:, None], cand[:, None], gi, torch.tensor([t], device=q.device), m=int(ni.k), cap=cap, raw_window=st.rw) row = torch.full((B, G), cap, dtype=torch.int32, device=q.device) row.scatter_(1, ids[:, 0], off[:, 0].to(torch.int32)) hit = torch.zeros(B, n, dtype=torch.bool, device=q.device) for li in range(int(gi.codes.shape[0])): # overlapping pages: a token is a member once per layer c = gi.codes[li, :, :n].long() gg = torch.div(c, ORD_MOD, rounding_mode="floor") hit |= (c >= 0) & (row.gather(1, gg.clamp(0, G - 1)) + (c - gg * ORD_MOD) < cap) raw = raw | (hit & same & ((t - jpos) >= st.rw)[None]) kk = torch.cat([K[:, :n], kap.to(K.dtype)], 1).float().repeat_interleave(rep, dim=2) # [B, n + C, h, dh] vv = torch.cat([V[:, :n], st.v_bar.to(V.dtype)], 1).float().repeat_interleave(rep, dim=2) ok = torch.cat([raw, vis], 1) lg = torch.einsum("bhd,bkhd->bhk", qf, kk) * dh ** -0.5 lg = lg.masked_fill(~ok[:, None], float("-inf")) o = torch.einsum("bhk,bkhd->bhd", torch.softmax(lg, -1), vv) return o[:, None].to(q.dtype) def _catalogue_read(self, q, K, V, r, t): st = self.cat opened = None if st.open: opened = note_open_table(q, st.kappa[r], st.ni, doc=st.doc, slot_close=st.slot_close, slot_doc=st.slot_doc, raw_window=st.rw, impl="list", q_offset=t, members=st.members) return attend_list(q, K, V, opened=opened, raw_window=st.rw, tag=st.tag, key_valid=None, extra_k=st.ek, extra_v=st.ev, q_offset=t) # ------------------------------------------------------------------ greedy decoding def _decode(self, h: torch.Tensor, new: int, eos: int, check: Optional[Callable[[torch.Tensor, int, torch.Tensor], torch.Tensor]] = None) -> int: """Greedy steps from the current position (`h`: the hidden state of the position before it). Writes the answer into the row and returns the position after its last token.""" cfg = self.cfg W = self.m.lm_head.weight out = self.buf B = out.shape[0] done = torch.zeros(B, dtype=torch.bool, device=out.device) t = int(self.t) for it in range(int(new)): if it: h = self.step(out[:, t - 1]) logits = F.linear(h, W).float() if cfg.logit_softcap: logits = cfg.logit_softcap * torch.tanh(logits / cfg.logit_softcap) nxt = logits.argmax(-1) nxt = torch.where(done, torch.full_like(nxt, eos), nxt) out[:, t] = nxt t += 1 done |= nxt == eos if check is not None: done = check(out, t, done) if bool(done.all()): break return t @torch.no_grad() def greedy(self, buf: torch.Tensor, doc: torch.Tensor, L0: int, new: int, *, eos: int, check: Optional[Callable[[torch.Tensor, int, torch.Tensor], torch.Tensor]] = None) -> torch.Tensor: """The uncached harness loop with a cache: buf / doc [B, Lb] as `_model_generate` builds them (prompt in [0, L0), eos and document βˆ’1 after). `check(buf, t, done)` β†’ done, after each written token (stop strings). Returns buf[:, :t] with the answer written, eos after a row's first eos.""" limit = self.max_new_tokens() if limit is not None and new > limit: _refuse(f"answers longer than {limit} tokens for this read") h = self.prefill(buf, doc, L0) t = self._decode(h, new, eos, check) return self.buf[:, :t] # ------------------------------------------------------------------ beam search @torch.no_grad() def reorder(self, rows: torch.Tensor) -> None: """Keep the batch rows `rows` [B'] (repeats allowed): πŸ€— beam search's cache reorder after each step (nn/perceiver_ar_hub.py, 2026-11-18). The cached keys and values, the reading layer's inputs, the row and its document ids are gathered; what the reading layer derives from many keys (LSA's buckets, the concepts and the reasoner's updates) is rebuilt from the gathered cache, as `step` rebuilds it at a block end. The closed blocks are the same as before, and the open block is read through its raw window until `step` rebuilds it at its end, so the next steps write what a decoding of the gathered rows would. The catalogue and notes reads keep notebooks per row that are not rebuilt here: refused.""" if self.kind in ("catalogue", "notes"): _refuse("reordering the rows of a notebook read (catalogue / notes)") rows = rows.to(device=self.buf.device, dtype=torch.long) def pick(x: torch.Tensor) -> torch.Tensor: return x.index_select(0, rows) self.buf, self.doc, self._ds0 = pick(self.buf), pick(self.doc), pick(self._ds0) for store in (self.K, self.V, self.X): for key in list(store): store[key] = pick(store[key]) self._ds_cols = {j: pick(col) for j, col in self._ds_cols.items()} self.B = int(rows.numel()) if self.kind == "lsa": self._build_lsa() elif self.kind == "concept": self._build_concepts() # ------------------------------------------------------------------ read once, answer many _SHARED = ("m", "cfg", "kind", "gi") def snapshot(self) -> dict: """A copy of everything a step changes: the cached keys and values, the row, the reading layer's indexes. Taken after `prefill` over a document it is that document's cache; `restore` (or `ask`) starts from it.""" return _clone_state({k: v for k, v in self.__dict__.items() if k not in self._SHARED}) def restore(self, snap: dict) -> None: """Back to a snapshot (copied again, so the snapshot can be restored any number of times).""" for k in [k for k in self.__dict__ if k not in self._SHARED]: del self.__dict__[k] self.__dict__.update(_clone_state(snap)) @torch.no_grad() def feed(self, tokens: torch.Tensor) -> torch.Tensor: """Write `tokens` [B, n] (or [n], the same for every row) at the next positions, one step each, and return the final-norm hidden state of the last one [B, d]: the question after a cached document.""" if tokens.dim() == 1: tokens = tokens[None].expand(self.B, -1) if tokens.shape[1] == 0: raise ValueError("feed needs at least one token") tokens = tokens.to(self.buf.device) h = None for j in range(tokens.shape[1]): h = self.step(tokens[:, j]) return h @torch.no_grad() def ask(self, snap: dict, question: torch.Tensor, new: int, *, eos: int, check: Optional[Callable[[torch.Tensor, int, torch.Tensor], torch.Tensor]] = None) -> torch.Tensor: """One question from a document's cache: restore `snap` (taken after `prefill`), write the question, decode up to `new` tokens. Returns the answer tokens [B, ≀ new]. The prefilled row needs free slots for both: L0 + len(question) + new ≀ its length.""" n = int(question.shape[-1]) limit = self.max_new_tokens() if limit is not None and n + int(new) > limit: _refuse(f"question + answer longer than {limit} tokens for this read") self.restore(snap) if self.t + n + int(new) > self.S: raise ValueError(f"the row has {self.S - self.t} free slots; the question and answer need {n + int(new)}") h = self.feed(question) t0 = int(self.t) t = self._decode(h, new, eos, check) return self.buf[:, t0:t].clone() # ============================================================================================================== # nn/perceiver_ar_hub.py # ============================================================================================================== # πŸ€— Transformers interface for the Perceiver AR family (`nn/perceiver_ar_lm.py`): loading with # `AutoModelForCausalLM` and πŸ€— `generate` over the cached decoder (`nn/incremental.py`), 2026-11-18. # # Engineering spec: docs/engineering_specs/hub_from_pretrained_loading.md. `scripts/export_hub_model.py` vendors this # file, with the modules a checkpoint uses, into the flat `modeling_perceiver_ar.py` of a Hub repository, so a reader # loads a release with # # AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True, dtype=torch.bfloat16) # # and scores text with `labels=` or samples with `generate` (greedy, sampling, beam search, repetition penalty, ...). # # Scoring (`labels`, πŸ€— convention: the model shifts them, βˆ’100 is ignored): the mean next-token cross-entropy of the # trained distribution (tanh soft-capped logits), the per-token loss `load_perceiver_ar_for_eval` gives # (`return_per_token_loss`); the training z-loss is not added. Padding (attention_mask 0) becomes document id βˆ’1, as in # the harness: padded keys are never read, positions restart at the first real token, padded targets are ignored. # # Generation: `PerceiverARCache` is the `past_key_values` πŸ€— generate carries between steps. Its first forward is the # cached decoder's prefill over one fixed-length row (the prompt, then free slots written as eos with document id βˆ’1, # `GEN_PAD`-rounded: the harness geometry, `PerceiverARLMEval._model_generate`); every later forward runs only the new # position. The logits are the harness's (`F.linear(h, lm_head.weight)`, soft-capped), so πŸ€— greedy writes the tokens # of `IncrementalDecoder.greedy`. When the row is full, or a notebook read reaches its exact horizon # (`IncrementalDecoder.max_new_tokens`), the cache prefills again over the tokens written so far: the state a fresh # prefill of those tokens has. Beam search reorders the cache's rows (`IncrementalDecoder.reorder`). Reads the cached # decoder does not cover (`decode_kind` refuses, and the catalogue / notes reads under beam search) fall back to the # harness's uncached loop: every step reads the whole row again. # # `use_cache=False` (in `generate` or a plain call) is the model's own forward over the given ids (the scoring path). GEN_PAD = 256 # row lengths are multiples of this (PerceiverARLMEval.GEN_PAD): flex attention compiles per shape def _round_up(n: int, m: int) -> int: return -(-int(n) // m) * m def _softcap(logits: torch.Tensor, cap) -> torch.Tensor: return cap * torch.tanh(logits / cap) if cap else logits def _mask_to_doc(attention_mask: Optional[torch.Tensor]) -> Optional[torch.Tensor]: """attention_mask [B, S] β†’ document ids (0 = token, βˆ’1 = padding); None when nothing is padded (the model's own path for a plain row, so scoring is bit-identical to a call without a mask).""" if attention_mask is None or bool(attention_mask.bool().all()): return None return torch.where(attention_mask.bool(), 0, -1).long() class PerceiverARCache: """The decoder state πŸ€— `generate` carries in `past_key_values` (one per `generate` call). `dec` is the `IncrementalDecoder` after its prefill (None before it, or when `uncached`); `headroom` the free slots a prefill leaves after the prompt (`generate`'s max_new_tokens when known); `since` the tokens written since the last prefill; `W` the output matrix [V, H] the steps multiply by (computed once).""" is_compileable = False to_legacy_cache = None # read by generate's `return_legacy_cache` check def __init__(self, headroom: int = GEN_PAD): self.headroom = max(1, int(headroom)) self.dec: Optional[IncrementalDecoder] = None self.uncached = False self.row_len = 0 # uncached rows: the fixed row length (grown when the answer passes it) self.since = 0 self.W: Optional[torch.Tensor] = None def get_seq_length(self, layer_idx: int = 0) -> int: return 0 if self.dec is None else int(self.dec.t) def reorder_cache(self, beam_idx: torch.Tensor) -> None: if self.dec is None: return try: self.dec.reorder(beam_idx) except NotImplementedError: # a notebook read: the rest of this generate call reads the whole row per step self.dec, self.uncached = None, True class PerceiverARForCausalLM(PerceiverARLM, GenerationMixin): """`PerceiverARLM` with the πŸ€— causal-LM interface: the same modules and state-dict keys, so a `perceiver_ar` checkpoint loads as it is; `forward` takes `labels`, `attention_mask`, `past_key_values`, `use_cache` and `logits_to_keep`, and `generate` is πŸ€—'s (the repo's own uncached probe sampler is `PerceiverARLM.generate`).""" _gen_headroom: Optional[int] = None @classmethod def _supports_default_dynamic_cache(cls) -> bool: return False # the cache is ours: made by prepare_inputs_for_generation / the first forward def generate(self, *args, **kwargs): """πŸ€— `GenerationMixin.generate`. Reads `max_new_tokens` only to size the cached row once (no re-prefill).""" gc = kwargs.get("generation_config") if gc is None and len(args) > 1: gc = args[1] new = kwargs.get("max_new_tokens", getattr(gc if gc is not None else self.generation_config, "max_new_tokens", None)) self._gen_headroom = int(new) if new else GEN_PAD try: return GenerationMixin.generate(self, *args, **kwargs) finally: self._gen_headroom = None def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, logits_to_keep=None, inputs_embeds=None, **kwargs): if inputs_embeds is not None: raise ValueError("PerceiverARForCausalLM reads token ids; inputs_embeds is not supported") if use_cache and not isinstance(past_key_values, PerceiverARCache): if past_key_values is not None and int(getattr(past_key_values, "get_seq_length", lambda: 0)() or 0): raise ValueError(f"past_key_values must be a PerceiverARCache, got {type(past_key_values).__name__}") past_key_values = PerceiverARCache(self._gen_headroom or GEN_PAD) return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values, "use_cache": use_cache, "logits_to_keep": logits_to_keep} # The parameters πŸ€— generate may pass are listed by name: no **kwargs, because the πŸ€— Trainer treats a forward with # **kwargs as one that normalises its own loss over the accumulation steps (PerceiverARLM.forward's note). def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, past_key_values: Optional[PerceiverARCache] = None, use_cache: Optional[bool] = None, logits_to_keep: Union[int, torch.Tensor, None] = 0, doc_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, # ignored: positions restart at each document start cache_position: Optional[torch.Tensor] = None, # ignored: the cache counts the written positions itself output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> CausalLMOutputWithPast: if inputs_embeds is not None or input_ids is None: raise ValueError("PerceiverARForCausalLM reads token ids (input_ids); inputs_embeds is not supported") if output_attentions or output_hidden_states: raise ValueError("output_attentions / output_hidden_states are not returned by this model") keep = 0 if logits_to_keep is None else logits_to_keep if use_cache is None: use_cache = past_key_values is not None cfg = self.config if use_cache and labels is None: if not isinstance(past_key_values, PerceiverARCache): if past_key_values is not None and int(past_key_values.get_seq_length() or 0): raise ValueError("past_key_values must be a PerceiverARCache") past_key_values = PerceiverARCache() h = self._cached_hidden(input_ids, attention_mask, past_key_values, keep) if isinstance(keep, int) and keep > 0: h = h[:, -keep:] elif torch.is_tensor(keep): h = h[:, keep] if past_key_values.W is None: past_key_values.W = self.lm_head.weight.detach() logits = _softcap(F.linear(h, past_key_values.W).float(), cfg.logit_softcap) return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values) doc = doc_ids if doc_ids is not None else _mask_to_doc(attention_mask) h = self.hidden_states(input_ids, doc_ids=doc) head_w, head_in = self._head_parts() loss = None if labels is not None: tgt = labels.to(h.device)[:, 1:] if attention_mask is not None: # no padded target, and no target read from a padded position m = attention_mask.to(h.device).bool() tgt = tgt.masked_fill(~(m[:, 1:] & m[:, :-1]), -100) per = per_token_ce_chunked(head_in(h[:, :-1]), head_w, tgt, cfg.chunked_ce_block_size, cfg.logit_softcap) loss = per.sum() / (tgt != -100).sum().clamp(min=1) if isinstance(keep, int) and keep > 0: h = h[:, -keep:] elif torch.is_tensor(keep): h = h[:, keep] logits = _softcap(F.linear(head_in(h), head_w).float(), cfg.logit_softcap) return CausalLMOutputWithPast(loss=loss, logits=logits) # ------------------------------------------------------------------ cached decoding def _eos(self) -> int: e = self.config.eos_token_id if isinstance(e, (list, tuple)): e = e[0] if e else None return int(self.config.pad_token_id if e is None else e) def _row(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor], S: int): """The harness row: ids in [0, L), eos after; document ids 0 (βˆ’1 where the mask is 0), βˆ’1 after.""" B, L = input_ids.shape buf = input_ids.new_full((B, S), self._eos()) buf[:, :L] = input_ids doc = torch.full((B, S), -1, dtype=torch.long, device=input_ids.device) doc[:, :L] = 0 if attention_mask is None else torch.where(attention_mask.to(input_ids.device).bool(), 0, -1) return buf, doc def _cached_hidden(self, input_ids, attention_mask, cache: PerceiverARCache, keep) -> torch.Tensor: """Final-norm hidden states [B, n, d] of the positions this call adds (after a prefill: the prompt's last position when `keep` is 1, as in πŸ€— generate, else every prompt position).""" B, L = input_ids.shape if cache.uncached: return self._uncached_hidden(input_ids, attention_mask, cache) dec = cache.dec n_new = L - (int(dec.t) if dec is not None else 0) limit = dec.max_new_tokens() if dec is not None else None if (dec is None or n_new <= 0 or L > dec.S or dec.B != B or (limit is not None and cache.since + n_new > limit)): try: dec = IncrementalDecoder(self) except NotImplementedError: cache.dec, cache.uncached = None, True return self._uncached_hidden(input_ids, attention_mask, cache) buf, doc = self._row(input_ids, attention_mask, _round_up(L + cache.headroom, GEN_PAD)) all_positions = not (isinstance(keep, int) and keep == 1) h = dec.prefill(buf, doc, L, all_positions=all_positions) cache.dec, cache.since = dec, 0 return h if all_positions else h[:, None] hs = [dec.step(input_ids[:, j]) for j in range(int(dec.t), L)] cache.since += n_new return torch.stack(hs, 1) @torch.no_grad() def _uncached_hidden(self, input_ids, attention_mask, cache: PerceiverARCache) -> torch.Tensor: """The harness's uncached step: the whole row again, one fixed length for the answer (grown by `GEN_PAD` when the answer passes it); the hidden state of the last position [B, 1, d].""" L = input_ids.shape[1] if cache.row_len < L: cache.row_len = _round_up(L + (cache.headroom if cache.row_len == 0 else GEN_PAD), GEN_PAD) buf, doc = self._row(input_ids, attention_mask, cache.row_len) return self.hidden_states(buf, doc_ids=doc)[:, L - 1:L] __all__ = ["PerceiverARConfig", "PerceiverARForCausalLM", "PerceiverARCache"]