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81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""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 <h_j, e_{w_j}> (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)