"""G1-FS16 nucleus: M3 byte re-decoding executor + order-sensitive slot compiler (spec v4.3, G1-FS16 preregistration). This replaces the falsified G1-DR field. The three registered defects it repairs, by construction: * ORDERED WORDS. The compiler scores a word as a sum of per-slot dot products (slots encoded by ONE stationary projection of the spine's own residual, codes as exchangeable embeddings, one shared blank embedding for empty slots) — s(PQ) != s(QP), permutation- equivariant, extrapolates to any preregistered depth cap with no learned length bias. * TRUE M3 EXECUTION. A word acts on a byte through the chain u_0 = S(x); v_j = F_{w_j}(u_{j-1}); l_j = b(x_{j-1}) + T_fix(v_j - u_{j-1}); p_j = softmax(l_j); soft re-seed u_j = sum_z p_j(z) S_z (training) hard re-seed u_j = S(argmax p_j) (deploy) where b is the model's OWN context-free byte decode (spine embed -> rmsnorm -> head, shared tensors, no recurrence): it cannot see the program, so the ONLY program-dependent path into an answer byte is the latched word. The empty word contributes exactly b(x) — zero correction. T_fix is fixed at init and never trained: no learned head can turn the displacement readout into a lookup. * EXCHANGEABLE, FULL-RANK ACTIONS. F_k = I + near-zero iid init, one per code, no code-specific meaning anywhere; full rank by preregistration so "rank starvation" is not an available excuse. A0: every trainable tensor here is gradient-traceable from the exact event codelength; the executor receives only carrier + exchangeable code index; the compiler reads only the spine's own residual at fixed-stride program slots; deploy is hard argmax. """ from __future__ import annotations import math from dataclasses import dataclass from typing import List, Optional, Tuple import torch from torch import Tensor, nn class _STOneHot(torch.autograd.Function): """Exact one-hot forward, identity backward onto the softmax.""" @staticmethod def forward(ctx, soft: Tensor) -> Tensor: return torch.nn.functional.one_hot( soft.argmax(-1), soft.shape[-1]).to(soft.dtype) @staticmethod def backward(ctx, grad: Tensor) -> Tensor: return grad def _haar(n: int, c: int) -> Tensor: """n Haar-distributed orthogonal c x c matrices.""" q, r = torch.linalg.qr(torch.randn(n, c, c)) return q * torch.sign(torch.diagonal(r, dim1=-2, dim2=-1)).unsqueeze(-2) @dataclass(frozen=True) class M3Config: d_model: int # spine residual width (compiler input) n_codes: int = 2 carrier: int = 256 d_compile: int = 32 # slot/code embedding width n_slots: int = 16 # program slot count (fixed-stride law) train_depth: int = 10 # words up to this depth are trained closure_depth: int = 16 # preregistered global cap (eval closure) tie_actions: bool = False # DENSE-SHARED control: one shared action act_init: float = 4.0 # Haar scale on F_k = I + act_init * Q_k byte_local: bool = True # stationary compiler; False replays the 24k matrix class M3Field(nn.Module): def __init__(self, cfg: M3Config): super().__init__() self.cfg = cfg C, K = cfg.carrier, cfg.n_codes self.S = nn.Parameter(torch.randn(256, C) * (1.0 / math.sqrt(C))) eye = torch.eye(C) n_act = 1 if cfg.tie_actions else K # Actions start SEPARATED, not near-identity. At the old scale # (0.02/sqrt(C)) the displacement logits of two different codes had # std 0.0013 against base logits of std 0.16, so no gradient could # tell the codes apart and the compiler had nothing to select # between: the field sat idle because it was born degenerate, not # because compression declined to use it. A Haar-orthogonal # perturbation keeps every action invertible (the semigroup stays a # group at init) while putting the codes O(1) apart. self.F_raw = nn.Parameter( eye.unsqueeze(0).repeat(n_act, 1, 1) + cfg.act_init * _haar(n_act, C)) T = torch.randn(256, C) / math.sqrt(C) self.register_buffer("T_fix", T, persistent=True) # never trained # Exactly ONE compiler is allocated. Carrying both would leave a # trainable tensor in the checkpoint that no term of L_PC can reach, # which the A0 gradient-traceability audit rejects -- correctly. # Byte-local compiler. The contextual compiler reads causal spine # states, so the SAME program byte can select different codes after # different prefixes and nothing forces w(uv) = w(u)w(v). That let the # optimizer settle on prefix-dependent partial programs which raise # exact-match while destroying word purity -- one of the two failure # signatures of the 24k matrix. Reading the raw byte embedding makes # the symbol map stationary by construction, so concatenation holds # mechanically rather than by hope. # # A0: this supplies no code meanings and no labels. One embedding and # one scorer serve all 256 bytes, the code columns stay exchangeable, # and its gradient arrives only through R_A / the mirror step and the # shared byte likelihood. if cfg.byte_local: self.E_byte = nn.Parameter(torch.randn(256, cfg.d_compile) * 0.2) self.W_b = nn.Linear(cfg.d_compile, cfg.d_compile, bias=False) else: self.W_c = nn.Linear(cfg.d_model, cfg.d_compile, bias=False) self.e_code = nn.Parameter(torch.randn(K, cfg.d_compile) * 0.2) self.e_blank = nn.Parameter(torch.randn(cfg.d_compile) * 0.2) self._plan_cache: dict = {} @property def F(self) -> Tensor: """Per-code actions; DENSE-SHARED ties every code to one action.""" if self.cfg.tie_actions: return self.F_raw.expand(self.cfg.n_codes, -1, -1) return self.F_raw # ---------------- compiler ---------------- def _symbols(self) -> Tensor: return torch.cat([self.e_code, self.e_blank.unsqueeze(0)], dim=0) def slot_logits(self, prog_states: Tensor) -> Tensor: """CONTEXTUAL compiler, retained for the registered 24k matrix only. (B, n_slots, d_model) spine residuals at program slots -> (B, n_slots, K+1) per-slot symbol scores (last column = blank). Prefer `slot_logits_bytes`: this reads causal spine state, so the symbol map is not stationary and concatenation is not guaranteed.""" if self.cfg.byte_local: raise RuntimeError( "contextual compiler not allocated under byte_local=True; " "set M3Config(byte_local=False) to replay the 24k matrix") h = self.W_c(prog_states) / math.sqrt(self.cfg.d_compile) return torch.einsum("bsd,kd->bsk", h, self._symbols()) def slot_logits_bytes(self, prog_bytes: Tensor) -> Tensor: """Byte-local compiler: (B, n_slots) int64 program bytes -> (B, n_slots, K+1) per-slot symbol scores. Depends on the current byte alone, so g(v) = argmax_k s(v, k) is a fixed symbol map and w(c_1..c_d) = g(c_1)..g(c_d) holds mechanically. The only residual ambiguity is the legitimate global permutation of code identities, which the controls already account for.""" if not self.cfg.byte_local: raise RuntimeError("byte-local compiler not allocated") r = self.E_byte[prog_bytes] h = self.W_b(r) / math.sqrt(self.cfg.d_compile) return torch.einsum("bsd,kd->bsk", h, self._symbols()) def word_scores(self, slot_logits: Tensor, words: List[Tuple[int, ...]]) -> Tensor: """Score every word: sum over its code slots + blanks after.""" B, S, _ = slot_logits.shape K = self.cfg.n_codes blank = slot_logits[:, :, K] # (B,S) blank_suffix = torch.flip( torch.cumsum(torch.flip(blank, [1]), dim=1), [1]) zero = torch.zeros(B, 1, device=slot_logits.device, dtype=slot_logits.dtype) blank_suffix = torch.cat([blank_suffix, zero], dim=1) # (B,S+1) scores = [] for w in words: s = blank_suffix[:, len(w)] for j, c in enumerate(w): s = s + slot_logits[:, j, c] scores.append(s) return torch.stack(scores, dim=1) # (B,W) def word_scores_indexed(self, slot_logits: Tensor, onehot: Tensor) -> Tensor: """Vectorized `word_scores` for a large fixed alphabet. `onehot` is (W, n_slots, K+1): slot j of word w selects its code for j < |w| and the blank symbol for j >= |w|. Mathematically identical to `word_scores`, which the tests pin. """ return torch.einsum("bsk,wsk->bw", slot_logits, onehot) def alphabet_onehot(self, words: List[Tuple[int, ...]]) -> Tensor: K, S = self.cfg.n_codes, self.cfg.n_slots oh = torch.zeros(len(words), S, K + 1) for w, word in enumerate(words): for j in range(S): oh[w, j, word[j] if j < len(word) else K] = 1.0 return oh def argmax_word(self, slot_logits: Tensor) -> List[Tuple[int, ...]]: """Exact hard argmax over the FULL closure alphabet, factorized: the best word of each length d takes the per-slot best code for slots < d and blanks after; then argmax over d <= closure cap.""" B, S, _ = slot_logits.shape K = self.cfg.n_codes best_code, best_idx = slot_logits[:, :, :K].max(dim=2) # (B,S) blank = slot_logits[:, :, K] code_prefix = torch.cumsum(best_code, dim=1) zero = torch.zeros(B, 1, device=slot_logits.device, dtype=slot_logits.dtype) code_prefix = torch.cat([zero, code_prefix], dim=1) # (B,S+1) blank_suffix = torch.flip( torch.cumsum(torch.flip(blank, [1]), dim=1), [1]) blank_suffix = torch.cat([blank_suffix, zero], dim=1) D = self.cfg.closure_depth totals = torch.stack( [code_prefix[:, d] + blank_suffix[:, d] for d in range(D + 1)], dim=1) # (B,D+1) dbest = totals.argmax(dim=1) out: List[Tuple[int, ...]] = [] for b in range(B): d = int(dbest[b]) out.append(tuple(int(best_idx[b, j]) for j in range(d))) return out # ---------------- executor ---------------- @staticmethod def _straight_through(soft: Tensor) -> Tensor: """One-hot forward, softmax gradient backward. The M3 bottleneck is only a BYTE if the training forward pass is the deploy forward pass. With a soft mixture the carrier is re-seeded from a convex combination of all 256 byte embeddings, which carries far more than 8 bits and is strictly more expressive than anything deploy can do — the relaxation is a continuous scratchpad, and the entropy charge was the price levied to discourage using it. Forcing the forward pass onto the one-hot removes the scratchpad by construction instead of by price, so train and deploy compute the identical function and the charge has nothing left to buy. A custom Function rather than the usual `oh + p - p.detach()`: that idiom evaluates (oh + p) - p in floating point and is NOT exactly oh, so the train/deploy identity would hold only to ~1e-7. The identity is the entire justification for dropping the entropy charge, so it is made exact. """ return _STOneHot.apply(soft) def chain(self, x: Tensor, word: Tuple[int, ...], base_fn, hard: bool, st: bool = False ) -> Tuple[Tensor, Tensor]: """Run the M3 chain for one word on a batch of bytes x (N,). Returns (final_logits (N,256), total_intermediate_entropy (N,)). `base_fn(probs_or_ids)` returns the model's own context-free decode logits either from hard ids (N,) or soft byte probs (N,256). """ N = x.shape[0] u = self.S[x] # (N,C) ent = x.new_zeros(N, dtype=torch.float32) prev_hard: Optional[Tensor] = x prev_soft: Optional[Tensor] = None logits = base_fn(x) # empty word for j, c in enumerate(word): v = torch.einsum("cd,nd->nc", self.F[c], u) base = base_fn(prev_hard if prev_soft is None else prev_soft) logits = base + torch.einsum("zc,nc->nz", self.T_fix, v - u) p = torch.softmax(logits, dim=-1) if j < len(word) - 1: ent = ent + (-(p * (p + 1e-12).log()).sum(-1) / math.log(2.0)) if hard: prev_hard, prev_soft = logits.argmax(-1), None u = self.S[prev_hard] elif st: thru = self._straight_through(p) prev_soft, prev_hard = thru, None u = thru @ self.S else: prev_soft, prev_hard = p, None u = p @ self.S return logits, ent def _tree_plan(self, words: List[Tuple[int, ...]], device: torch.device) -> "_TreePlan": key = (tuple(words), str(device)) plan = self._plan_cache.get(key) if plan is None: plan = _TreePlan(words, self.cfg.n_codes, device) self._plan_cache[key] = plan return plan def tree_execute(self, x: Tensor, words: List[Tuple[int, ...]], base_fn, hard: bool = False, st: bool = False ) -> Tuple[Tensor, Tensor]: """Execute EVERY word in `words` on bytes x, sharing prefixes. `words` must be prefix-closed and contain the empty word. Each prefix's chain step runs exactly once, so an alphabet of 2^(D+1)-1 words costs 2^(D+1)-1 steps rather than sum |w|. Returns per-word (FULL M3 logits (W,N,256), intermediate entropy (W,N)) — the same quantity `chain` returns, so the two are interchangeable and the oracle's capacity certificate transfers. This used to return only the final step's DISPLACEMENT, leaving the caller to supply a base. The probe supplied the spine's contextual answer logits, which silently replaced the law's own b(z_{L-1}) term: latent execution then differed from the executor the oracle certifies, so the certificate guaranteed nothing about what was actually measured. The base belongs to the law, not to the caller. A displacement, if one is wanted, is `logits - base_fn(x)` which is exactly zero for the empty word. The walk runs one DEPTH LEVEL at a time, not one word at a time: every node at a level shares the same handful of code actions, so a level is a constant number of batched kernels regardless of its width. Word-at-a-time was arithmetically identical but issued ~5 tiny kernels per node, and at the registered alphabet (2,047 words) that launch overhead measured 3.7 s per training step on a T4 — a 25-hour run for the preregistered 24k steps. """ plan = self._tree_plan(words, x.device) N = x.shape[0] dt = self.S.dtype root_logits = base_fn(x) # (N,256) u = self.S[x].unsqueeze(0) # (1,N,C) feed: Optional[Tensor] = None # what base_fn re-reads; None = x soft: Optional[Tensor] = None # softmax, charged by lam_mid ent_lvl = x.new_zeros(1, N, dtype=torch.float32) logit_levels = [root_logits.unsqueeze(0)] ent_levels = [ent_lvl] for lvl in range(1, plan.depth + 1): par, counts = plan.parent[lvl], plan.counts[lvl] u_par = u.index_select(0, par) # (M,N,C) outs, start = [], 0 for k in range(self.cfg.n_codes): m = counts[k] if m == 0: continue outs.append(torch.einsum( "cd,mnd->mnc", self.F[k], u_par[start:start + m])) start += m v = torch.cat(outs, dim=0) if len(outs) > 1 else outs[0] d = torch.einsum("zc,mnc->mnz", self.T_fix, v - u_par) M = d.shape[0] if feed is None: # parents = empty base = root_logits.unsqueeze(0).expand(M, N, 256) ent_child = ent_lvl.index_select(0, par) else: base = base_fn(feed.index_select(0, par).reshape(M * N, 256) ).reshape(M, N, 256) # the MDL charge is on the model's UNCERTAINTY at the # re-seed point, which is the softmax even when the # carrier is re-seeded from the hard byte sp = soft.index_select(0, par) # (M,N,256) h = -(sp * (sp + 1e-12).log()).sum(-1) / math.log(2.0) ent_child = ent_lvl.index_select(0, par) + h node_logits = base + d logit_levels.append(node_logits) ent_levels.append(ent_child) if lvl < plan.depth: logits = node_logits soft = torch.softmax(logits, dim=-1) if hard: hb = logits.argmax(-1) u = self.S[hb] feed = torch.nn.functional.one_hot(hb, 256).to(dt) elif st: feed = self._straight_through(soft) u = feed @ self.S else: u = soft @ self.S feed = soft ent_lvl = ent_child out = torch.cat(logit_levels, dim=0).index_select(0, plan.order) ent = torch.cat(ent_levels, dim=0).index_select(0, plan.order) return out, ent class _TreePlan: """Static level structure of a prefix-closed alphabet. Nodes at each level are held grouped by last code so a level's actions are a few contiguous slices instead of a per-node gather of (C,C) matrices, which would materialize K^depth copies of the action. """ def __init__(self, words: List[Tuple[int, ...]], n_codes: int, device: torch.device): if () not in words: raise ValueError("alphabet must contain the empty word") self.depth = max(len(w) for w in words) levels: List[List[Tuple[int, ...]]] = [[] for _ in range(self.depth + 1)] for w in words: levels[len(w)].append(w) for lvl in range(1, self.depth + 1): levels[lvl].sort(key=lambda w: w[-1]) pos = [{w: i for i, w in enumerate(lv)} for lv in levels] self.parent: List[Optional[Tensor]] = [None] self.counts: List[Optional[List[int]]] = [None] for lvl in range(1, self.depth + 1): par = [] for w in levels[lvl]: if w[:-1] not in pos[lvl - 1]: raise ValueError(f"alphabet is not prefix-closed: {w}") par.append(pos[lvl - 1][w[:-1]]) self.parent.append(torch.tensor(par, dtype=torch.long, device=device)) self.counts.append([sum(1 for w in levels[lvl] if w[-1] == k) for k in range(n_codes)]) offset, flat = 0, {} for lv in levels: for i, w in enumerate(lv): flat[w] = offset + i offset += len(lv) self.order = torch.tensor([flat[w] for w in words], dtype=torch.long, device=device)