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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""G1-FS16 nucleus: M3 byte re-decoding executor + order-sensitive slot
|
| 2 |
+
compiler (spec v4.3, G1-FS16 preregistration).
|
| 3 |
+
|
| 4 |
+
This replaces the falsified G1-DR field. The three registered defects it
|
| 5 |
+
repairs, by construction:
|
| 6 |
+
|
| 7 |
+
* ORDERED WORDS. The compiler scores a word as a sum of per-slot dot
|
| 8 |
+
products <h_j, e_{w_j}> (slots encoded by ONE stationary projection of
|
| 9 |
+
the spine's own residual, codes as exchangeable embeddings, one shared
|
| 10 |
+
blank embedding for empty slots) — s(PQ) != s(QP), permutation-
|
| 11 |
+
equivariant, extrapolates to any preregistered depth cap with no
|
| 12 |
+
learned length bias.
|
| 13 |
+
* TRUE M3 EXECUTION. A word acts on a byte through the chain
|
| 14 |
+
u_0 = S(x); v_j = F_{w_j}(u_{j-1});
|
| 15 |
+
l_j = b(x_{j-1}) + T_fix(v_j - u_{j-1}); p_j = softmax(l_j);
|
| 16 |
+
soft re-seed u_j = sum_z p_j(z) S_z (training)
|
| 17 |
+
hard re-seed u_j = S(argmax p_j) (deploy)
|
| 18 |
+
where b is the model's OWN context-free byte decode (spine embed ->
|
| 19 |
+
rmsnorm -> head, shared tensors, no recurrence): it cannot see the
|
| 20 |
+
program, so the ONLY program-dependent path into an answer byte is the
|
| 21 |
+
latched word. The empty word contributes exactly b(x) — zero
|
| 22 |
+
correction. T_fix is fixed at init and never trained: no learned head
|
| 23 |
+
can turn the displacement readout into a lookup.
|
| 24 |
+
* EXCHANGEABLE, FULL-RANK ACTIONS. F_k = I + near-zero iid init, one per
|
| 25 |
+
code, no code-specific meaning anywhere; full rank by preregistration
|
| 26 |
+
so "rank starvation" is not an available excuse.
|
| 27 |
+
|
| 28 |
+
A0: every trainable tensor here is gradient-traceable from the exact
|
| 29 |
+
event codelength; the executor receives only carrier + exchangeable code
|
| 30 |
+
index; the compiler reads only the spine's own residual at fixed-stride
|
| 31 |
+
program slots; deploy is hard argmax.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import math
|
| 37 |
+
from dataclasses import dataclass
|
| 38 |
+
from typing import List, Optional, Tuple
|
| 39 |
+
|
| 40 |
+
import torch
|
| 41 |
+
from torch import Tensor, nn
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class _STOneHot(torch.autograd.Function):
|
| 45 |
+
"""Exact one-hot forward, identity backward onto the softmax."""
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def forward(ctx, soft: Tensor) -> Tensor:
|
| 49 |
+
return torch.nn.functional.one_hot(
|
| 50 |
+
soft.argmax(-1), soft.shape[-1]).to(soft.dtype)
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def backward(ctx, grad: Tensor) -> Tensor:
|
| 54 |
+
return grad
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _haar(n: int, c: int) -> Tensor:
|
| 58 |
+
"""n Haar-distributed orthogonal c x c matrices."""
|
| 59 |
+
q, r = torch.linalg.qr(torch.randn(n, c, c))
|
| 60 |
+
return q * torch.sign(torch.diagonal(r, dim1=-2, dim2=-1)).unsqueeze(-2)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(frozen=True)
|
| 64 |
+
class M3Config:
|
| 65 |
+
d_model: int # spine residual width (compiler input)
|
| 66 |
+
n_codes: int = 2
|
| 67 |
+
carrier: int = 256
|
| 68 |
+
d_compile: int = 32 # slot/code embedding width
|
| 69 |
+
n_slots: int = 16 # program slot count (fixed-stride law)
|
| 70 |
+
train_depth: int = 10 # words up to this depth are trained
|
| 71 |
+
closure_depth: int = 16 # preregistered global cap (eval closure)
|
| 72 |
+
tie_actions: bool = False # DENSE-SHARED control: one shared action
|
| 73 |
+
act_init: float = 4.0 # Haar scale on F_k = I + act_init * Q_k
|
| 74 |
+
byte_local: bool = True # stationary compiler; False replays the 24k matrix
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class M3Field(nn.Module):
|
| 78 |
+
def __init__(self, cfg: M3Config):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.cfg = cfg
|
| 81 |
+
C, K = cfg.carrier, cfg.n_codes
|
| 82 |
+
self.S = nn.Parameter(torch.randn(256, C) * (1.0 / math.sqrt(C)))
|
| 83 |
+
eye = torch.eye(C)
|
| 84 |
+
n_act = 1 if cfg.tie_actions else K
|
| 85 |
+
# Actions start SEPARATED, not near-identity. At the old scale
|
| 86 |
+
# (0.02/sqrt(C)) the displacement logits of two different codes had
|
| 87 |
+
# std 0.0013 against base logits of std 0.16, so no gradient could
|
| 88 |
+
# tell the codes apart and the compiler had nothing to select
|
| 89 |
+
# between: the field sat idle because it was born degenerate, not
|
| 90 |
+
# because compression declined to use it. A Haar-orthogonal
|
| 91 |
+
# perturbation keeps every action invertible (the semigroup stays a
|
| 92 |
+
# group at init) while putting the codes O(1) apart.
|
| 93 |
+
self.F_raw = nn.Parameter(
|
| 94 |
+
eye.unsqueeze(0).repeat(n_act, 1, 1)
|
| 95 |
+
+ cfg.act_init * _haar(n_act, C))
|
| 96 |
+
T = torch.randn(256, C) / math.sqrt(C)
|
| 97 |
+
self.register_buffer("T_fix", T, persistent=True) # never trained
|
| 98 |
+
# Exactly ONE compiler is allocated. Carrying both would leave a
|
| 99 |
+
# trainable tensor in the checkpoint that no term of L_PC can reach,
|
| 100 |
+
# which the A0 gradient-traceability audit rejects -- correctly.
|
| 101 |
+
# Byte-local compiler. The contextual compiler reads causal spine
|
| 102 |
+
# states, so the SAME program byte can select different codes after
|
| 103 |
+
# different prefixes and nothing forces w(uv) = w(u)w(v). That let the
|
| 104 |
+
# optimizer settle on prefix-dependent partial programs which raise
|
| 105 |
+
# exact-match while destroying word purity -- one of the two failure
|
| 106 |
+
# signatures of the 24k matrix. Reading the raw byte embedding makes
|
| 107 |
+
# the symbol map stationary by construction, so concatenation holds
|
| 108 |
+
# mechanically rather than by hope.
|
| 109 |
+
#
|
| 110 |
+
# A0: this supplies no code meanings and no labels. One embedding and
|
| 111 |
+
# one scorer serve all 256 bytes, the code columns stay exchangeable,
|
| 112 |
+
# and its gradient arrives only through R_A / the mirror step and the
|
| 113 |
+
# shared byte likelihood.
|
| 114 |
+
if cfg.byte_local:
|
| 115 |
+
self.E_byte = nn.Parameter(torch.randn(256, cfg.d_compile) * 0.2)
|
| 116 |
+
self.W_b = nn.Linear(cfg.d_compile, cfg.d_compile, bias=False)
|
| 117 |
+
else:
|
| 118 |
+
self.W_c = nn.Linear(cfg.d_model, cfg.d_compile, bias=False)
|
| 119 |
+
self.e_code = nn.Parameter(torch.randn(K, cfg.d_compile) * 0.2)
|
| 120 |
+
self.e_blank = nn.Parameter(torch.randn(cfg.d_compile) * 0.2)
|
| 121 |
+
self._plan_cache: dict = {}
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def F(self) -> Tensor:
|
| 125 |
+
"""Per-code actions; DENSE-SHARED ties every code to one action."""
|
| 126 |
+
if self.cfg.tie_actions:
|
| 127 |
+
return self.F_raw.expand(self.cfg.n_codes, -1, -1)
|
| 128 |
+
return self.F_raw
|
| 129 |
+
|
| 130 |
+
# ---------------- compiler ----------------
|
| 131 |
+
def _symbols(self) -> Tensor:
|
| 132 |
+
return torch.cat([self.e_code, self.e_blank.unsqueeze(0)], dim=0)
|
| 133 |
+
|
| 134 |
+
def slot_logits(self, prog_states: Tensor) -> Tensor:
|
| 135 |
+
"""CONTEXTUAL compiler, retained for the registered 24k matrix only.
|
| 136 |
+
|
| 137 |
+
(B, n_slots, d_model) spine residuals at program slots ->
|
| 138 |
+
(B, n_slots, K+1) per-slot symbol scores (last column = blank).
|
| 139 |
+
Prefer `slot_logits_bytes`: this reads causal spine state, so the
|
| 140 |
+
symbol map is not stationary and concatenation is not guaranteed."""
|
| 141 |
+
if self.cfg.byte_local:
|
| 142 |
+
raise RuntimeError(
|
| 143 |
+
"contextual compiler not allocated under byte_local=True; "
|
| 144 |
+
"set M3Config(byte_local=False) to replay the 24k matrix")
|
| 145 |
+
h = self.W_c(prog_states) / math.sqrt(self.cfg.d_compile)
|
| 146 |
+
return torch.einsum("bsd,kd->bsk", h, self._symbols())
|
| 147 |
+
|
| 148 |
+
def slot_logits_bytes(self, prog_bytes: Tensor) -> Tensor:
|
| 149 |
+
"""Byte-local compiler: (B, n_slots) int64 program bytes ->
|
| 150 |
+
(B, n_slots, K+1) per-slot symbol scores.
|
| 151 |
+
|
| 152 |
+
Depends on the current byte alone, so g(v) = argmax_k s(v, k) is a
|
| 153 |
+
fixed symbol map and w(c_1..c_d) = g(c_1)..g(c_d) holds mechanically.
|
| 154 |
+
The only residual ambiguity is the legitimate global permutation of
|
| 155 |
+
code identities, which the controls already account for."""
|
| 156 |
+
if not self.cfg.byte_local:
|
| 157 |
+
raise RuntimeError("byte-local compiler not allocated")
|
| 158 |
+
r = self.E_byte[prog_bytes]
|
| 159 |
+
h = self.W_b(r) / math.sqrt(self.cfg.d_compile)
|
| 160 |
+
return torch.einsum("bsd,kd->bsk", h, self._symbols())
|
| 161 |
+
|
| 162 |
+
def word_scores(self, slot_logits: Tensor,
|
| 163 |
+
words: List[Tuple[int, ...]]) -> Tensor:
|
| 164 |
+
"""Score every word: sum over its code slots + blanks after."""
|
| 165 |
+
B, S, _ = slot_logits.shape
|
| 166 |
+
K = self.cfg.n_codes
|
| 167 |
+
blank = slot_logits[:, :, K] # (B,S)
|
| 168 |
+
blank_suffix = torch.flip(
|
| 169 |
+
torch.cumsum(torch.flip(blank, [1]), dim=1), [1])
|
| 170 |
+
zero = torch.zeros(B, 1, device=slot_logits.device,
|
| 171 |
+
dtype=slot_logits.dtype)
|
| 172 |
+
blank_suffix = torch.cat([blank_suffix, zero], dim=1) # (B,S+1)
|
| 173 |
+
scores = []
|
| 174 |
+
for w in words:
|
| 175 |
+
s = blank_suffix[:, len(w)]
|
| 176 |
+
for j, c in enumerate(w):
|
| 177 |
+
s = s + slot_logits[:, j, c]
|
| 178 |
+
scores.append(s)
|
| 179 |
+
return torch.stack(scores, dim=1) # (B,W)
|
| 180 |
+
|
| 181 |
+
def word_scores_indexed(self, slot_logits: Tensor,
|
| 182 |
+
onehot: Tensor) -> Tensor:
|
| 183 |
+
"""Vectorized `word_scores` for a large fixed alphabet.
|
| 184 |
+
|
| 185 |
+
`onehot` is (W, n_slots, K+1): slot j of word w selects its code
|
| 186 |
+
for j < |w| and the blank symbol for j >= |w|. Mathematically
|
| 187 |
+
identical to `word_scores`, which the tests pin.
|
| 188 |
+
"""
|
| 189 |
+
return torch.einsum("bsk,wsk->bw", slot_logits, onehot)
|
| 190 |
+
|
| 191 |
+
def alphabet_onehot(self, words: List[Tuple[int, ...]]) -> Tensor:
|
| 192 |
+
K, S = self.cfg.n_codes, self.cfg.n_slots
|
| 193 |
+
oh = torch.zeros(len(words), S, K + 1)
|
| 194 |
+
for w, word in enumerate(words):
|
| 195 |
+
for j in range(S):
|
| 196 |
+
oh[w, j, word[j] if j < len(word) else K] = 1.0
|
| 197 |
+
return oh
|
| 198 |
+
|
| 199 |
+
def argmax_word(self, slot_logits: Tensor) -> List[Tuple[int, ...]]:
|
| 200 |
+
"""Exact hard argmax over the FULL closure alphabet, factorized:
|
| 201 |
+
the best word of each length d takes the per-slot best code for
|
| 202 |
+
slots < d and blanks after; then argmax over d <= closure cap."""
|
| 203 |
+
B, S, _ = slot_logits.shape
|
| 204 |
+
K = self.cfg.n_codes
|
| 205 |
+
best_code, best_idx = slot_logits[:, :, :K].max(dim=2) # (B,S)
|
| 206 |
+
blank = slot_logits[:, :, K]
|
| 207 |
+
code_prefix = torch.cumsum(best_code, dim=1)
|
| 208 |
+
zero = torch.zeros(B, 1, device=slot_logits.device,
|
| 209 |
+
dtype=slot_logits.dtype)
|
| 210 |
+
code_prefix = torch.cat([zero, code_prefix], dim=1) # (B,S+1)
|
| 211 |
+
blank_suffix = torch.flip(
|
| 212 |
+
torch.cumsum(torch.flip(blank, [1]), dim=1), [1])
|
| 213 |
+
blank_suffix = torch.cat([blank_suffix, zero], dim=1)
|
| 214 |
+
D = self.cfg.closure_depth
|
| 215 |
+
totals = torch.stack(
|
| 216 |
+
[code_prefix[:, d] + blank_suffix[:, d] for d in range(D + 1)],
|
| 217 |
+
dim=1) # (B,D+1)
|
| 218 |
+
dbest = totals.argmax(dim=1)
|
| 219 |
+
out: List[Tuple[int, ...]] = []
|
| 220 |
+
for b in range(B):
|
| 221 |
+
d = int(dbest[b])
|
| 222 |
+
out.append(tuple(int(best_idx[b, j]) for j in range(d)))
|
| 223 |
+
return out
|
| 224 |
+
|
| 225 |
+
# ---------------- executor ----------------
|
| 226 |
+
@staticmethod
|
| 227 |
+
def _straight_through(soft: Tensor) -> Tensor:
|
| 228 |
+
"""One-hot forward, softmax gradient backward.
|
| 229 |
+
|
| 230 |
+
The M3 bottleneck is only a BYTE if the training forward pass is the
|
| 231 |
+
deploy forward pass. With a soft mixture the carrier is re-seeded
|
| 232 |
+
from a convex combination of all 256 byte embeddings, which carries
|
| 233 |
+
far more than 8 bits and is strictly more expressive than anything
|
| 234 |
+
deploy can do — the relaxation is a continuous scratchpad, and the
|
| 235 |
+
entropy charge was the price levied to discourage using it. Forcing
|
| 236 |
+
the forward pass onto the one-hot removes the scratchpad by
|
| 237 |
+
construction instead of by price, so train and deploy compute the
|
| 238 |
+
identical function and the charge has nothing left to buy.
|
| 239 |
+
|
| 240 |
+
A custom Function rather than the usual `oh + p - p.detach()`: that
|
| 241 |
+
idiom evaluates (oh + p) - p in floating point and is NOT exactly oh,
|
| 242 |
+
so the train/deploy identity would hold only to ~1e-7. The identity
|
| 243 |
+
is the entire justification for dropping the entropy charge, so it
|
| 244 |
+
is made exact.
|
| 245 |
+
"""
|
| 246 |
+
return _STOneHot.apply(soft)
|
| 247 |
+
|
| 248 |
+
def chain(self, x: Tensor, word: Tuple[int, ...],
|
| 249 |
+
base_fn, hard: bool, st: bool = False
|
| 250 |
+
) -> Tuple[Tensor, Tensor]:
|
| 251 |
+
"""Run the M3 chain for one word on a batch of bytes x (N,).
|
| 252 |
+
|
| 253 |
+
Returns (final_logits (N,256), total_intermediate_entropy (N,)).
|
| 254 |
+
`base_fn(probs_or_ids)` returns the model's own context-free
|
| 255 |
+
decode logits either from hard ids (N,) or soft byte probs
|
| 256 |
+
(N,256).
|
| 257 |
+
"""
|
| 258 |
+
N = x.shape[0]
|
| 259 |
+
u = self.S[x] # (N,C)
|
| 260 |
+
ent = x.new_zeros(N, dtype=torch.float32)
|
| 261 |
+
prev_hard: Optional[Tensor] = x
|
| 262 |
+
prev_soft: Optional[Tensor] = None
|
| 263 |
+
logits = base_fn(x) # empty word
|
| 264 |
+
for j, c in enumerate(word):
|
| 265 |
+
v = torch.einsum("cd,nd->nc", self.F[c], u)
|
| 266 |
+
base = base_fn(prev_hard if prev_soft is None else prev_soft)
|
| 267 |
+
logits = base + torch.einsum("zc,nc->nz", self.T_fix, v - u)
|
| 268 |
+
p = torch.softmax(logits, dim=-1)
|
| 269 |
+
if j < len(word) - 1:
|
| 270 |
+
ent = ent + (-(p * (p + 1e-12).log()).sum(-1)
|
| 271 |
+
/ math.log(2.0))
|
| 272 |
+
if hard:
|
| 273 |
+
prev_hard, prev_soft = logits.argmax(-1), None
|
| 274 |
+
u = self.S[prev_hard]
|
| 275 |
+
elif st:
|
| 276 |
+
thru = self._straight_through(p)
|
| 277 |
+
prev_soft, prev_hard = thru, None
|
| 278 |
+
u = thru @ self.S
|
| 279 |
+
else:
|
| 280 |
+
prev_soft, prev_hard = p, None
|
| 281 |
+
u = p @ self.S
|
| 282 |
+
return logits, ent
|
| 283 |
+
|
| 284 |
+
def _tree_plan(self, words: List[Tuple[int, ...]],
|
| 285 |
+
device: torch.device) -> "_TreePlan":
|
| 286 |
+
key = (tuple(words), str(device))
|
| 287 |
+
plan = self._plan_cache.get(key)
|
| 288 |
+
if plan is None:
|
| 289 |
+
plan = _TreePlan(words, self.cfg.n_codes, device)
|
| 290 |
+
self._plan_cache[key] = plan
|
| 291 |
+
return plan
|
| 292 |
+
|
| 293 |
+
def tree_execute(self, x: Tensor, words: List[Tuple[int, ...]],
|
| 294 |
+
base_fn, hard: bool = False, st: bool = False
|
| 295 |
+
) -> Tuple[Tensor, Tensor]:
|
| 296 |
+
"""Execute EVERY word in `words` on bytes x, sharing prefixes.
|
| 297 |
+
|
| 298 |
+
`words` must be prefix-closed and contain the empty word. Each
|
| 299 |
+
prefix's chain step runs exactly once, so an alphabet of
|
| 300 |
+
2^(D+1)-1 words costs 2^(D+1)-1 steps rather than sum |w|.
|
| 301 |
+
Returns per-word (FULL M3 logits (W,N,256), intermediate entropy
|
| 302 |
+
(W,N)) — the same quantity `chain` returns, so the two are
|
| 303 |
+
interchangeable and the oracle's capacity certificate transfers.
|
| 304 |
+
|
| 305 |
+
This used to return only the final step's DISPLACEMENT, leaving the
|
| 306 |
+
caller to supply a base. The probe supplied the spine's contextual
|
| 307 |
+
answer logits, which silently replaced the law's own
|
| 308 |
+
b(z_{L-1}) term: latent execution then differed from the executor
|
| 309 |
+
the oracle certifies, so the certificate guaranteed nothing about
|
| 310 |
+
what was actually measured. The base belongs to the law, not to
|
| 311 |
+
the caller. A displacement, if one is wanted, is `logits - base_fn(x)`
|
| 312 |
+
which is exactly zero for the empty word.
|
| 313 |
+
|
| 314 |
+
The walk runs one DEPTH LEVEL at a time, not one word at a time:
|
| 315 |
+
every node at a level shares the same handful of code actions, so
|
| 316 |
+
a level is a constant number of batched kernels regardless of its
|
| 317 |
+
width. Word-at-a-time was arithmetically identical but issued
|
| 318 |
+
~5 tiny kernels per node, and at the registered alphabet
|
| 319 |
+
(2,047 words) that launch overhead measured 3.7 s per training
|
| 320 |
+
step on a T4 — a 25-hour run for the preregistered 24k steps.
|
| 321 |
+
"""
|
| 322 |
+
plan = self._tree_plan(words, x.device)
|
| 323 |
+
N = x.shape[0]
|
| 324 |
+
dt = self.S.dtype
|
| 325 |
+
root_logits = base_fn(x) # (N,256)
|
| 326 |
+
u = self.S[x].unsqueeze(0) # (1,N,C)
|
| 327 |
+
feed: Optional[Tensor] = None # what base_fn re-reads; None = x
|
| 328 |
+
soft: Optional[Tensor] = None # softmax, charged by lam_mid
|
| 329 |
+
ent_lvl = x.new_zeros(1, N, dtype=torch.float32)
|
| 330 |
+
logit_levels = [root_logits.unsqueeze(0)]
|
| 331 |
+
ent_levels = [ent_lvl]
|
| 332 |
+
|
| 333 |
+
for lvl in range(1, plan.depth + 1):
|
| 334 |
+
par, counts = plan.parent[lvl], plan.counts[lvl]
|
| 335 |
+
u_par = u.index_select(0, par) # (M,N,C)
|
| 336 |
+
outs, start = [], 0
|
| 337 |
+
for k in range(self.cfg.n_codes):
|
| 338 |
+
m = counts[k]
|
| 339 |
+
if m == 0:
|
| 340 |
+
continue
|
| 341 |
+
outs.append(torch.einsum(
|
| 342 |
+
"cd,mnd->mnc", self.F[k], u_par[start:start + m]))
|
| 343 |
+
start += m
|
| 344 |
+
v = torch.cat(outs, dim=0) if len(outs) > 1 else outs[0]
|
| 345 |
+
d = torch.einsum("zc,mnc->mnz", self.T_fix, v - u_par)
|
| 346 |
+
M = d.shape[0]
|
| 347 |
+
|
| 348 |
+
if feed is None: # parents = empty
|
| 349 |
+
base = root_logits.unsqueeze(0).expand(M, N, 256)
|
| 350 |
+
ent_child = ent_lvl.index_select(0, par)
|
| 351 |
+
else:
|
| 352 |
+
base = base_fn(feed.index_select(0, par).reshape(M * N, 256)
|
| 353 |
+
).reshape(M, N, 256)
|
| 354 |
+
# the MDL charge is on the model's UNCERTAINTY at the
|
| 355 |
+
# re-seed point, which is the softmax even when the
|
| 356 |
+
# carrier is re-seeded from the hard byte
|
| 357 |
+
sp = soft.index_select(0, par) # (M,N,256)
|
| 358 |
+
h = -(sp * (sp + 1e-12).log()).sum(-1) / math.log(2.0)
|
| 359 |
+
ent_child = ent_lvl.index_select(0, par) + h
|
| 360 |
+
node_logits = base + d
|
| 361 |
+
logit_levels.append(node_logits)
|
| 362 |
+
ent_levels.append(ent_child)
|
| 363 |
+
|
| 364 |
+
if lvl < plan.depth:
|
| 365 |
+
logits = node_logits
|
| 366 |
+
soft = torch.softmax(logits, dim=-1)
|
| 367 |
+
if hard:
|
| 368 |
+
hb = logits.argmax(-1)
|
| 369 |
+
u = self.S[hb]
|
| 370 |
+
feed = torch.nn.functional.one_hot(hb, 256).to(dt)
|
| 371 |
+
elif st:
|
| 372 |
+
feed = self._straight_through(soft)
|
| 373 |
+
u = feed @ self.S
|
| 374 |
+
else:
|
| 375 |
+
u = soft @ self.S
|
| 376 |
+
feed = soft
|
| 377 |
+
ent_lvl = ent_child
|
| 378 |
+
|
| 379 |
+
out = torch.cat(logit_levels, dim=0).index_select(0, plan.order)
|
| 380 |
+
ent = torch.cat(ent_levels, dim=0).index_select(0, plan.order)
|
| 381 |
+
return out, ent
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class _TreePlan:
|
| 385 |
+
"""Static level structure of a prefix-closed alphabet.
|
| 386 |
+
|
| 387 |
+
Nodes at each level are held grouped by last code so a level's actions
|
| 388 |
+
are a few contiguous slices instead of a per-node gather of (C,C)
|
| 389 |
+
matrices, which would materialize K^depth copies of the action.
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
def __init__(self, words: List[Tuple[int, ...]], n_codes: int,
|
| 393 |
+
device: torch.device):
|
| 394 |
+
if () not in words:
|
| 395 |
+
raise ValueError("alphabet must contain the empty word")
|
| 396 |
+
self.depth = max(len(w) for w in words)
|
| 397 |
+
levels: List[List[Tuple[int, ...]]] = [[] for _ in
|
| 398 |
+
range(self.depth + 1)]
|
| 399 |
+
for w in words:
|
| 400 |
+
levels[len(w)].append(w)
|
| 401 |
+
for lvl in range(1, self.depth + 1):
|
| 402 |
+
levels[lvl].sort(key=lambda w: w[-1])
|
| 403 |
+
pos = [{w: i for i, w in enumerate(lv)} for lv in levels]
|
| 404 |
+
|
| 405 |
+
self.parent: List[Optional[Tensor]] = [None]
|
| 406 |
+
self.counts: List[Optional[List[int]]] = [None]
|
| 407 |
+
for lvl in range(1, self.depth + 1):
|
| 408 |
+
par = []
|
| 409 |
+
for w in levels[lvl]:
|
| 410 |
+
if w[:-1] not in pos[lvl - 1]:
|
| 411 |
+
raise ValueError(f"alphabet is not prefix-closed: {w}")
|
| 412 |
+
par.append(pos[lvl - 1][w[:-1]])
|
| 413 |
+
self.parent.append(torch.tensor(par, dtype=torch.long,
|
| 414 |
+
device=device))
|
| 415 |
+
self.counts.append([sum(1 for w in levels[lvl] if w[-1] == k)
|
| 416 |
+
for k in range(n_codes)])
|
| 417 |
+
|
| 418 |
+
offset, flat = 0, {}
|
| 419 |
+
for lv in levels:
|
| 420 |
+
for i, w in enumerate(lv):
|
| 421 |
+
flat[w] = offset + i
|
| 422 |
+
offset += len(lv)
|
| 423 |
+
self.order = torch.tensor([flat[w] for w in words],
|
| 424 |
+
dtype=torch.long, device=device)
|