farguney commited on
Commit
a8c6b98
·
verified ·
1 Parent(s): 482e70b

Upload jobs/g1fs16_probe.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. jobs/g1fs16_probe.py +1005 -0
jobs/g1fs16_probe.py ADDED
@@ -0,0 +1,1005 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = [
5
+ # "torch>=2.2",
6
+ # "numpy>=1.23",
7
+ # "huggingface_hub>=0.24",
8
+ # ]
9
+ # ///
10
+ """G1-FS16: the corrected emergence instrument (spec v4.3 prereg).
11
+
12
+ Question, unchanged: does compression pressure ALONE bind an operator
13
+ field, shown by compositional generalization no matched control reaches?
14
+
15
+ What makes this instrument different from the falsified G1-DR probe:
16
+
17
+ * MAP-FAMILY EXPLOSION. Operators are two SHA256-derived random
18
+ permutations of all 256 byte values. Training covers every word of
19
+ depth 0..10 -- 2,047 DISTINCT random permutations, ~4.2 Mbit of
20
+ incompressible map content. A d=64 spine cannot store that, but it
21
+ can store two generators (~4 kbit) if the field binds them. Binding
22
+ is not merely possible, it is the only affordable encoding.
23
+ * GENUINELY JOINT EVENTS. One latent word governs M records that share
24
+ a program, so the event marginal spans M*8 answer bytes.
25
+ * ORDER-SENSITIVE COMPILER + TRUE M3 EXECUTION (trident/nucleus5m3.py),
26
+ repairing the two structural defects that made G1-DR's negative
27
+ uninformative.
28
+ * CLOSURE EVALUATION. Words of depth 11..16 are never trained; the
29
+ preregistered global cap is 16, the same frozen tensors execute, and
30
+ evaluation adds no weights and no routing.
31
+
32
+ Oracle certificate runs FIRST and is a training-only diagnostic under
33
+ the 9.3 control rules: if the executor cannot represent the maps under
34
+ forced words, the apparatus is invalid and no G1 evidence exists.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import hashlib
40
+ import itertools
41
+ import json
42
+ import math
43
+ import os
44
+ import sys
45
+ import time
46
+ from typing import Dict, List, Optional, Tuple
47
+
48
+ import numpy as np
49
+ import torch
50
+ from huggingface_hub import HfApi
51
+ from torch import Tensor, nn
52
+
53
+ SRC_REPO = os.environ.get("TRIDENT_SRC_REPO", "farguney/trident-src")
54
+ try:
55
+ import trident # noqa: F401
56
+ except ModuleNotFoundError:
57
+ from huggingface_hub import snapshot_download
58
+
59
+ sys.path.insert(0, snapshot_download(
60
+ repo_id=SRC_REPO, repo_type="model",
61
+ revision=os.environ.get("TRIDENT_SRC_REVISION")))
62
+
63
+ from trident.core5 import BOS_ID, Core5, Core5Config # noqa: E402
64
+ from trident.nucleus5m3 import M3Config, M3Field # noqa: E402
65
+
66
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
67
+
68
+ ARM = os.environ.get("FS16_ARM", "field")
69
+ SEEDS = [int(s) for s in os.environ.get("FS16_SEEDS", "0").split(",")]
70
+ STEPS = int(os.environ.get("FS16_STEPS", "24000"))
71
+ EVENTS = int(os.environ.get("FS16_EVENTS", "2")) # logical events/step
72
+ M_REC = int(os.environ.get("FS16_M", "16")) # records per event
73
+ LR = float(os.environ.get("FS16_LR", "1e-3"))
74
+ COMP_LR = float(os.environ.get("FS16_COMP_LR", "1e-4"))
75
+ D_MODEL = int(os.environ.get("FS16_D", "64"))
76
+ N_LAYERS = int(os.environ.get("FS16_LAYERS", "3"))
77
+ CARRIER = int(os.environ.get("FS16_CARRIER", "256"))
78
+ D_COMPILE = int(os.environ.get("FS16_DC", "32"))
79
+ TRAIN_DEPTH = int(os.environ.get("FS16_TRAIN_DEPTH", "10"))
80
+ CLOSURE = int(os.environ.get("FS16_CLOSURE", "16"))
81
+ N_SLOTS = int(os.environ.get("FS16_SLOTS", "16"))
82
+ LAM_MID = float(os.environ.get("FS16_LAM_MID", "1.0"))
83
+ LAM_CPU = float(os.environ.get("FS16_LAM_CPU", "0.02"))
84
+ LAM_A = float(os.environ.get("FS16_LAM_A", "0.02"))
85
+ # Cold-start schedules (training-only; the model never observes either
86
+ # variable, and both end at the registered stationary objective).
87
+ # MID_WARMUP: fraction of training over which lam_mid ramps 0 -> LAM_MID.
88
+ # At init the intermediate distributions are near-uniform, so the full
89
+ # charge prices a depth-10 word at ~64*8*9 = 4608 bits against 0 for
90
+ # the empty word, an order of magnitude more than the ~512 bits of
91
+ # answer content any word could ever win. That is an initialization
92
+ # artifact, not a description length: nothing is being transmitted yet.
93
+ # CURRIC: fraction over which the trained depth grows 1 -> TRAIN_DEPTH,
94
+ # with the alphabet tracking it. Pure data ordering plus a schedule on
95
+ # a preregistered hypothesis-space cap; codes stay exchangeable.
96
+ MID_WARMUP = float(os.environ.get("FS16_MID_WARMUP", "0.3"))
97
+ CURRIC = float(os.environ.get("FS16_CURRIC", "0.5"))
98
+ # ST: run the training forward pass through the EXACT deploy bottleneck (a
99
+ # one-hot byte) with the softmax gradient, instead of a soft mixture. The
100
+ # entropy charge exists only because the soft relaxation re-seeds the
101
+ # carrier from a convex combination of all 256 byte embeddings, which
102
+ # carries far more than 8 bits and is a continuous scratchpad deploy cannot
103
+ # use. Straight-through removes that gap by construction, at which point
104
+ # lam_mid has nothing left to buy and the honest remaining price of an
105
+ # intermediate is CPU, which LAM_CPU already charges: at deploy the byte is
106
+ # recomputed deterministically from weights the decoder already holds, so
107
+ # no intermediate is ever transmitted and no codelength is owed for it.
108
+ ST = os.environ.get("FS16_ST", "0") == "1"
109
+ # ST_AFTER: fraction of training after which the forward pass switches from
110
+ # the soft mixture to the exact one-hot. Straight-through alone measured
111
+ # WORSE than the soft path at matched step and depth (byte 0.253 vs 0.971 at
112
+ # step 5000, depth 4): the one-hot forward is exact but its gradient is
113
+ # biased, and early on the mixture's gradient is what breaks the code
114
+ # symmetry. Only the DEPLOYED model has to satisfy train == deploy; the
115
+ # path there does not. Annealing soft -> one-hot ends at the exact identity,
116
+ # so the final claim is clean, no entropy charge is ever levied, and the
117
+ # early gradient is unbiased. 0 = one-hot from the start, 1 = never.
118
+ ST_AFTER = float(os.environ.get("FS16_ST_AFTER", "0"))
119
+ # ACT_INIT: F_k = I + ACT_INIT * Q_k with Q_k Haar-orthogonal. At the old
120
+ # near-identity scale two codes' displacement logits differed by std 0.0001
121
+ # against base logits of 0.16 -- 1600x too small for a gradient to tell the
122
+ # codes apart, which is the real reason the field sat idle. Measured
123
+ # separations: 0.0001 (old) / 0.20 (2.0) / 0.40 (4.0), min singular value
124
+ # 3.0 at 4.0 so every action is invertible at init.
125
+ ACT_INIT = float(os.environ.get("FS16_ACT_INIT", "4.0"))
126
+ # SAMPLED: send executor gradient through ONE posterior-sampled word per
127
+ # event rather than the full q-weighted marginal. Same expected gradient
128
+ # (q is the posterior, so the envelope theorem applies) but the realized
129
+ # update is a coherent program instead of the posterior-mean of 2047 words.
130
+ SAMPLED = os.environ.get("FS16_SAMPLED", "1") == "1"
131
+ NO_PUSH = os.environ.get("FS16_NO_PUSH", "0") == "1"
132
+ # Optimizer schedule. OFF by default: the registered 24k matrix ran with a
133
+ # constant LR and its law must stay reproducible. A schedule carries no task,
134
+ # label, reward, or semantic signal and changes no tensor's provenance, so it
135
+ # is A0-neutral -- it is an optimizer setting, not a training signal.
136
+ COSINE = os.environ.get("FS16_COSINE", "0") == "1"
137
+ # --- the board's repair set for FS16-UNSTABLE (all default ON; setting all
138
+ # --- three to 0 with COSINE=0 reproduces the registered 24k matrix exactly)
139
+ # Byte-local compiler: stationary symbol map, so concatenation is mechanical.
140
+ BYTE_LOCAL = os.environ.get("FS16_BYTE_LOCAL", "1") == "1"
141
+ # Rate barrier on the posterior. beta*log2(W/eps) = 61.3 bits at beta=4 must
142
+ # be paid before an alternative word can displace the incumbent, which stops
143
+ # hard EM from locking onto a random alias. A STRICTER R_A charge, never weaker.
144
+ BETA_A = float(os.environ.get("FS16_BETA_A", "4.0"))
145
+ # Per-group gradient clipping instead of one global norm.
146
+ GROUP_CLIP = os.environ.get("FS16_GROUP_CLIP", "1") == "1"
147
+ # Frozen, domain-separated evaluation panel; evaluation never touches train RNG.
148
+ FROZEN_PANEL = os.environ.get("FS16_FROZEN_PANEL", "1") == "1"
149
+ LR_WARMUP = int(os.environ.get("FS16_LR_WARMUP", "500"))
150
+ LR_FLOOR = float(os.environ.get("FS16_LR_FLOOR", "0.02"))
151
+ EPS = float(os.environ.get("FS16_EPS", "0.05"))
152
+ EVAL_EVERY = int(os.environ.get("FS16_EVAL_EVERY", "1000"))
153
+ # evaluation sample sizes; a reading must be able to carry a gate
154
+ EVAL_WORDS = int(os.environ.get("FS16_EVAL_WORDS", "4"))
155
+ EVAL_EVENTS_PER_WORD = int(os.environ.get("FS16_EVAL_EVENTS", "2"))
156
+ EVAL_BIND = int(os.environ.get("FS16_EVAL_BIND", "16"))
157
+ EVAL_PURITY = int(os.environ.get("FS16_EVAL_PURITY", "4"))
158
+ ORACLE_STEPS = int(os.environ.get("FS16_ORACLE_STEPS", "3000"))
159
+ ORACLE_ONLY = os.environ.get("FS16_ORACLE_ONLY", "0") == "1"
160
+ # 0.02 bits for every registered run; env override exists ONLY so the
161
+ # plumbing smoke can run at toy widths that cannot meet the certificate
162
+ ORACLE_ENT_TOL = float(os.environ.get("FS16_ORACLE_ENT_TOL", "0.02"))
163
+ RESULTS_REPO = os.environ.get("FS16_RESULTS_REPO", "deepadapt/trident-ec")
164
+
165
+ # The registered G1-FS16 certification geometry (10.5.2). Two independent
166
+ # accidents made this a structural matter rather than a naming convention:
167
+ # (i) every seed of an arm wrote to `g1fs16_{ARM}.json`, so three concurrent
168
+ # seed jobs silently overwrote each other and a 3/3-seed verdict could not be
169
+ # assembled from the artifacts at all; (ii) a toy-width CPU smoke published
170
+ # over a registered field artifact, and it differed only in
171
+ # m_records/carrier/closure/slots -- nothing a reader of the filename could
172
+ # have noticed. So the path now carries the seed, and any deviation from the
173
+ # geometry below is diverted to `scratch/` at construction time. Publishing
174
+ # correctly is no longer something anyone has to remember to do.
175
+ CERT_GEOMETRY = {"events": 2, "m_records": 16, "d": 64, "layers": 3,
176
+ "carrier": 256, "train_depth": 10, "closure": 16,
177
+ "slots": 16}
178
+
179
+
180
+ def _geometry() -> Dict[str, int]:
181
+ return {"events": EVENTS, "m_records": M_REC, "d": D_MODEL,
182
+ "layers": N_LAYERS, "carrier": CARRIER,
183
+ "train_depth": TRAIN_DEPTH, "closure": CLOSURE, "slots": N_SLOTS}
184
+
185
+
186
+ def _off_law() -> Dict[str, str]:
187
+ """Law-bearing dimensions in which this run departs from the registered
188
+ geometry. Empty for a certification run."""
189
+ live = _geometry()
190
+ return {k: f"{live[k]} != {v}"
191
+ for k, v in CERT_GEOMETRY.items() if live[k] != v}
192
+
193
+
194
+ OFF_LAW = _off_law()
195
+ RESULT_FILE = os.environ.get("FS16_RESULT_FILE") or (
196
+ ("scratch/" if OFF_LAW else "")
197
+ + f"g1fs16_{ARM}_s{'-'.join(str(s) for s in SEEDS)}.json")
198
+ NONCE_MAX = int(os.environ.get("FS16_NONCE_MAX", "32"))
199
+
200
+ REC_LEN = 32
201
+ N_PAIRS = 8
202
+ PROG_BYTES = 16
203
+ PAD = ord(".")
204
+ K_CODES = 2
205
+
206
+ torch.set_float32_matmul_precision("high")
207
+
208
+
209
+ # ---------------------------------------------------------------------------
210
+ # corpus: collision-free free semigroup of random byte permutations
211
+ # ---------------------------------------------------------------------------
212
+
213
+ def _stream(nonce: int, gen: int, counter: int) -> int:
214
+ h = hashlib.sha256(
215
+ b"TRIDENT-G1-FS16-v1" + nonce.to_bytes(4, "big")
216
+ + gen.to_bytes(1, "big") + counter.to_bytes(8, "big")).digest()
217
+ return int.from_bytes(h[:8], "big")
218
+
219
+
220
+ def _permutation(nonce: int, gen: int) -> np.ndarray:
221
+ """Fisher-Yates with rejection sampling (never modulo-biased)."""
222
+ p = np.arange(256, dtype=np.uint8)
223
+ counter = 0
224
+ for i in range(255, 0, -1):
225
+ m = i + 1
226
+ limit = (1 << 64) - ((1 << 64) % m)
227
+ while True:
228
+ r = _stream(nonce, gen, counter)
229
+ counter += 1
230
+ if r < limit:
231
+ break
232
+ j = r % m
233
+ p[i], p[j] = p[j], p[i]
234
+ return p
235
+
236
+
237
+ def _closure_is_collision_free(perms: List[np.ndarray],
238
+ depth: int) -> bool:
239
+ """All words of depth 0..depth induce distinct permutations."""
240
+ seen = {np.arange(256, dtype=np.uint8).tobytes()}
241
+ frontier = [np.arange(256, dtype=np.uint8)]
242
+ for _ in range(depth):
243
+ nxt = []
244
+ for cur in frontier:
245
+ for p in perms:
246
+ comp = p[cur] # sigma_g o sigma_w
247
+ key = comp.tobytes()
248
+ if key in seen:
249
+ return False
250
+ seen.add(key)
251
+ nxt.append(comp)
252
+ frontier = nxt
253
+ return True
254
+
255
+
256
+ def find_nonce(depth: int) -> Tuple[int, List[np.ndarray]]:
257
+ for nonce in range(NONCE_MAX):
258
+ perms = [_permutation(nonce, g) for g in range(K_CODES)]
259
+ if _closure_is_collision_free(perms, depth):
260
+ return nonce, perms
261
+ raise RuntimeError("no collision-free nonce found")
262
+
263
+
264
+ def word_perm(perms: List[np.ndarray], w: Tuple[int, ...]) -> np.ndarray:
265
+ out = np.arange(256, dtype=np.uint8)
266
+ for g in w:
267
+ out = perms[g][out]
268
+ return out
269
+
270
+
271
+ def enumerate_words(depth_lo: int, depth_hi: int) -> List[Tuple[int, ...]]:
272
+ out: List[Tuple[int, ...]] = []
273
+ for d in range(depth_lo, depth_hi + 1):
274
+ if d == 0:
275
+ out.append(())
276
+ else:
277
+ out.extend(itertools.product(range(K_CODES), repeat=d))
278
+ return out
279
+
280
+
281
+ def make_event(word: Tuple[int, ...], perm: np.ndarray,
282
+ rng: np.random.Generator) -> np.ndarray:
283
+ """M records, 32 bytes each, sharing one program."""
284
+ prog = np.full(PROG_BYTES, PAD, dtype=np.uint8)
285
+ for j, g in enumerate(word):
286
+ prog[j] = ord("P") + g
287
+ xs = rng.integers(0, 256, size=(M_REC, N_PAIRS)).astype(np.uint8)
288
+ rec = np.empty((M_REC, REC_LEN), dtype=np.uint8)
289
+ rec[:, :PROG_BYTES] = prog
290
+ rec[:, PROG_BYTES::2] = xs
291
+ rec[:, PROG_BYTES + 1::2] = perm[xs]
292
+ return rec
293
+
294
+
295
+ # ---------------------------------------------------------------------------
296
+ # model
297
+ # ---------------------------------------------------------------------------
298
+
299
+ class FS16Probe(nn.Module):
300
+ def __init__(self, arm: str):
301
+ super().__init__()
302
+ self.arm = arm
303
+ self.spine = Core5(Core5Config(d_model=D_MODEL, n_layers=N_LAYERS))
304
+ self.field: Optional[M3Field] = None
305
+ if arm != "no_opfield":
306
+ self.field = M3Field(M3Config(
307
+ d_model=D_MODEL, n_codes=K_CODES, carrier=CARRIER,
308
+ d_compile=D_COMPILE, n_slots=N_SLOTS,
309
+ train_depth=TRAIN_DEPTH, closure_depth=CLOSURE,
310
+ tie_actions=(arm == "dense_shared"), act_init=ACT_INIT,
311
+ byte_local=BYTE_LOCAL))
312
+ if arm == "random_frozen":
313
+ self.field.F_raw.requires_grad_(False)
314
+ self.field.S.requires_grad_(False)
315
+
316
+ def base_decode(self, xb: Tensor) -> Tensor:
317
+ """The model's OWN context-free byte decode (shared tensors)."""
318
+ if xb.dtype == torch.long:
319
+ e = self.spine.embed(xb)
320
+ else:
321
+ e = xb @ self.spine.embed.weight[:256]
322
+ return self.spine.head(self.spine.norm_f(e))
323
+
324
+ def spine_pass(self, rec: Tensor) -> Tuple[Tensor, Tensor]:
325
+ """(B,32) records -> (logits (B,32,256), states (B,32,d))."""
326
+ B = rec.shape[0]
327
+ bos = torch.full((B, 1), BOS_ID, dtype=torch.long,
328
+ device=rec.device)
329
+ ids = torch.cat([bos, rec[:, :-1]], dim=1)
330
+ x = self.spine.embed(ids)
331
+ for n1, mix, n2, mlp in self.spine.blocks:
332
+ y, _ = mix(n1(x), None)
333
+ x = x + y
334
+ x = x + mlp(n2(x))
335
+ h = self.spine.norm_f(x)
336
+ return self.spine.head(h), h
337
+
338
+
339
+ def target_positions() -> Tuple[List[int], List[int]]:
340
+ xpos = [PROG_BYTES + 2 * j for j in range(N_PAIRS)]
341
+ ypos = [PROG_BYTES + 2 * j + 1 for j in range(N_PAIRS)]
342
+ return xpos, ypos
343
+
344
+
345
+ # ---------------------------------------------------------------------------
346
+ # oracle capacity certificate (training-only diagnostic, never deployed)
347
+ # ---------------------------------------------------------------------------
348
+
349
+ def oracle_certificate(model: FS16Probe, perms: List[np.ndarray],
350
+ seed: int) -> Dict[str, object]:
351
+ """Force singleton words; require exact composition to depth CLOSURE."""
352
+ field = model.field
353
+ params = [field.F_raw, field.S, model.spine.embed.weight,
354
+ model.spine.head.weight, model.spine.norm_f.g]
355
+ opt = torch.optim.AdamW([p for p in params if p.requires_grad],
356
+ lr=3e-3, weight_decay=0.0)
357
+ rng = np.random.default_rng(7000 + seed)
358
+ P = torch.from_numpy(np.stack(perms)).long().to(DEVICE)
359
+ for step in range(ORACLE_STEPS):
360
+ x = torch.from_numpy(
361
+ rng.integers(0, 256, size=256).astype(np.int64)).to(DEVICE)
362
+ loss = 0.0
363
+ for g in range(K_CODES):
364
+ logits, _ = field.chain(x, (g,), model.base_decode, hard=False)
365
+ loss = loss + torch.nn.functional.cross_entropy(
366
+ logits, P[g][x])
367
+ opt.zero_grad(set_to_none=True)
368
+ loss.backward()
369
+ opt.step()
370
+ if step % 500 == 0:
371
+ print(f"[oracle-s{seed}] step {step} loss {float(loss):.5f}",
372
+ flush=True)
373
+ allx = torch.arange(256, device=DEVICE)
374
+ worst_acc, worst_depth, max_ent = 1.0, -1, 0.0
375
+ with torch.no_grad():
376
+ for d in range(1, CLOSURE + 1):
377
+ probe = [tuple(rng.integers(0, K_CODES, size=d).tolist())
378
+ for _ in range(4)] if d > 3 else \
379
+ list(itertools.product(range(K_CODES), repeat=d))
380
+ for w in probe:
381
+ logits, ent = field.chain(allx, w, model.base_decode,
382
+ hard=True)
383
+ tgt = torch.from_numpy(
384
+ word_perm(perms, w).astype(np.int64)).to(DEVICE)
385
+ acc = float(logits.argmax(-1).eq(tgt).float().mean())
386
+ if acc < worst_acc:
387
+ worst_acc, worst_depth = acc, d
388
+ max_ent = max(max_ent, float(ent.max()) / max(1, d - 1))
389
+ ok = worst_acc >= 1.0 - 1e-9 and max_ent < ORACLE_ENT_TOL
390
+ print(f"[oracle-s{seed}] worst_acc={worst_acc:.4f} at depth "
391
+ f"{worst_depth}, max_mid_entropy={max_ent:.4f} -> "
392
+ f"{'PASS' if ok else 'FAIL'}", flush=True)
393
+ return {"worst_acc": worst_acc, "worst_depth": worst_depth,
394
+ "max_mid_entropy": max_ent, "pass": ok}
395
+
396
+
397
+ # ---------------------------------------------------------------------------
398
+ # primary training: exact event codelength
399
+ # ---------------------------------------------------------------------------
400
+
401
+ def _slot_logits(field, rec: Tensor, states: Tensor) -> Tensor:
402
+ """Compiler read, contextual or byte-local.
403
+
404
+ The contextual path reads causal spine state, so the same program byte can
405
+ map to different codes after different prefixes and w(uv) = w(u)w(v) is
406
+ not enforced -- the mechanism behind the purity failure in the registered
407
+ 24k matrix. The byte-local path makes the symbol map stationary by
408
+ construction. Default is byte-local; BYTE_LOCAL=0 reproduces the
409
+ registered matrix exactly."""
410
+ if BYTE_LOCAL:
411
+ return field.slot_logits_bytes(rec[:1, :N_SLOTS])
412
+ return field.slot_logits(states[:1, 1:1 + N_SLOTS])
413
+
414
+
415
+ def event_codelength(model: FS16Probe, rec: Tensor, words, onehot,
416
+ wlen: Tensor, salt: int, lam_mid: float = LAM_MID,
417
+ st: bool = ST) -> Tuple[Tensor, Tensor, Tensor]:
418
+ """Returns (prefix_bits scalar, per-word event bits (W,), prior (W,))."""
419
+ logits, states = model.spine_pass(rec)
420
+ logp = torch.log_softmax(logits.float(), -1)
421
+ nll = -logp.gather(2, rec.unsqueeze(2)).squeeze(2) / math.log(2.0)
422
+ xpos, ypos = target_positions()
423
+ prefix_bits = nll.sum() - nll[:, ypos].sum()
424
+
425
+ if model.field is None:
426
+ return prefix_bits, nll[:, ypos].sum().unsqueeze(0), \
427
+ torch.zeros(1, device=rec.device)
428
+
429
+ field = model.field
430
+ if model.arm == "shuffled":
431
+ g = torch.Generator().manual_seed(salt)
432
+ perm = torch.randperm(K_CODES, generator=g).tolist()
433
+ words_exec = [tuple(perm[c] for c in w) for w in words]
434
+ else:
435
+ words_exec = words
436
+
437
+ x = rec[:, xpos].reshape(-1) # (M*8,)
438
+ y = rec[:, ypos].reshape(-1)
439
+ # FULL M3 logits, exactly the executor the oracle certifies. The spine's
440
+ # contextual answer logits are deliberately NOT the base here: the law's
441
+ # own b(z_{L-1}) term is what the certificate covers, and substituting a
442
+ # contextual base made latent execution differ from the certified
443
+ # executor. It also makes the field's task strictly harder than the
444
+ # no-field control's, which keeps its contextual spine readout.
445
+ word_logits, ent = field.tree_execute(
446
+ x, words_exec, model.base_decode, hard=False, st=st)
447
+ lp = torch.log_softmax(word_logits.float(), -1)
448
+ ans_bits = -lp.gather(2, y.view(1, -1, 1).expand(lp.shape[0], -1, 1)
449
+ ).squeeze(2) / math.log(2.0) # (W,N)
450
+ per_word = (ans_bits.sum(1) + lam_mid * ent.sum(1)
451
+ + LAM_CPU * x.shape[0] * wlen
452
+ + LAM_A * wlen * math.log2(K_CODES))
453
+ prior = field.word_scores_indexed(_slot_logits(field, rec, states),
454
+ onehot).squeeze(0)
455
+ return prefix_bits, per_word, prior
456
+
457
+
458
+ PREFIX_R = float(os.environ.get("FS16_PREFIX_R", "0.5"))
459
+ STRATIFIED = os.environ.get("FS16_STRATIFIED", "1") == "1"
460
+
461
+
462
+ def _strata(words):
463
+ """Partition the enumerated support by length class: empty / 1 / >=2.
464
+
465
+ The strata are a property of the word lattice only -- lengths, nothing
466
+ else -- so stratifying carries no task signal and leaves the estimator
467
+ permutation-equivariant in the codes."""
468
+ lens = [len(w) for w in words]
469
+ masks = []
470
+ for pred in (lambda n: n == 0, lambda n: n == 1, lambda n: n >= 2):
471
+ m = torch.tensor([pred(n) for n in lens], device=DEVICE)
472
+ if bool(m.any()):
473
+ masks.append(m)
474
+ return masks
475
+
476
+
477
+ def _prefix_floor(words, depth):
478
+ """Exchangeable prefix-process floor rho_r over the enumerated words.
479
+
480
+ The uniform eps/W floor spreads exploration mass evenly over every word,
481
+ and because words of depth d outnumber shorter ones geometrically, almost
482
+ all of that mass lands on LONG random aliases while each single primitive
483
+ gets eps/W. At eps=0.05 over 2047 words a singleton floor is 2.4e-05, so
484
+ displacing a collapsed blank incumbent costs beta*log2(0.95/2.4e-05) = 61.3
485
+ bits -- and that is the same barrier that (correctly) stops random aliases.
486
+ Raising it protects against aliases and imprisons the first REAL code;
487
+ lowering it frees the code and reopens alias lock-in. Tuning beta cannot
488
+ separate them because it scales both.
489
+
490
+ Length can. Generate a word by stopping with probability (1-r), else
491
+ emitting one of K exchangeable codes, with forced termination at the cap:
492
+
493
+ rho_r(w) = (1-r) (r/K)^|w| |w| < D
494
+ = (r/K)^D |w| = D
495
+
496
+ which is normalized by construction. At r=1/2, K=2 a singleton floor is
497
+ eps/8 while a depth-10 alias floor is eps*(1/4)^10, so the singleton
498
+ barrier falls to 29.14 bits -- comfortably above the 15.9-bit largest
499
+ accidental advantage measured at init by scripts/beta_barrier.py -- while
500
+ the depth-10 alias barrier RISES to 97.14 bits. Escape and stability stop
501
+ competing.
502
+
503
+ A0: rho_r reads only K, D and |w|. It never sees a byte, a task id, a
504
+ label, an operator meaning or a verifier, and it is invariant under
505
+ relabelling of the codes, so it is an admissible R_A coding measure rather
506
+ than a task-shaped prior.
507
+ """
508
+ r, K = PREFIX_R, K_CODES
509
+ out = torch.empty(len(words), device=DEVICE)
510
+ for i, w in enumerate(words):
511
+ n = len(w)
512
+ if n >= depth:
513
+ lp = n * math.log(r / K)
514
+ else:
515
+ lp = math.log1p(-r) + n * math.log(r / K)
516
+ out[i] = lp
517
+ # renormalize over the ENUMERATED support: the cap means the tail beyond
518
+ # `depth` is unreachable here, and an unnormalized floor would silently
519
+ # change the total rate charge rather than only its shape.
520
+ out = out - torch.logsumexp(out, dim=0)
521
+ return out + math.log(EPS)
522
+
523
+
524
+ def train_one(seed: int, perms: List[np.ndarray],
525
+ out: Dict[str, object], on_progress=None
526
+ ) -> Dict[str, object]:
527
+ torch.manual_seed(seed)
528
+ model = FS16Probe(ARM).to(DEVICE)
529
+ out["seed"] = seed
530
+
531
+ if model.field is not None:
532
+ out["oracle"] = oracle_certificate(model, perms, seed)
533
+ # The certificate is a validity gate for the PRIMARY arm only: it
534
+ # asks whether the executor could represent the maps at all, so a
535
+ # failure there means the instrument is broken and no G1 evidence
536
+ # exists. For a control it asks nothing of the sort. RANDOM-FROZEN
537
+ # freezes the actions and DENSE-SHARED ties them to one, so both
538
+ # MUST fail a capacity certificate -- that failure IS the crippling
539
+ # the control exists to impose. Aborting them as invalid apparatus
540
+ # (which is what happened, silently, to both arms) would leave the
541
+ # purity comparison with no controls at all.
542
+ if ARM == "field" and not out["oracle"]["pass"]:
543
+ out["verdict"] = "INVALID-APPARATUS"
544
+ return out
545
+ if ORACLE_ONLY:
546
+ out["verdict"] = "ORACLE-ONLY"
547
+ return out
548
+ torch.manual_seed(seed) # discard oracle weights
549
+ model = FS16Probe(ARM).to(DEVICE)
550
+
551
+ # one alphabet per curriculum depth; each is prefix-closed, so the
552
+ # level-batched executor consumes it directly
553
+ alpha: Dict[int, Tuple] = {}
554
+ for dd in range(1, TRAIN_DEPTH + 1):
555
+ ws = enumerate_words(0, dd)
556
+ alpha[dd] = (
557
+ ws,
558
+ (model.field.alphabet_onehot(ws).to(DEVICE)
559
+ if model.field is not None else None),
560
+ torch.tensor([float(len(w)) for w in ws], device=DEVICE),
561
+ math.log(EPS / len(ws)),
562
+ _prefix_floor(ws, dd),
563
+ _strata(ws))
564
+
565
+ # EXHAUSTIVE OWNERSHIP, not suffix guessing.
566
+ #
567
+ # The previous partition looked for {"W_c.weight", "e_code", "e_blank"} --
568
+ # but under byte_local=True there IS no W_c, so the "compiler" group held
569
+ # only the two symbol vectors while `E_byte` and `W_b.weight` -- the exact
570
+ # parameters that let P, Q and PAD acquire DISTINCT representations -- fell
571
+ # into the spine group and were clipped against its ~3915 norm. `field.S`
572
+ # went with them. So the 2260x throttle was only half repaired: the symbol
573
+ # vectors were freed and the byte READER was not, which is why the seed born
574
+ # with a distinct map held while the blank-born seeds could never repair
575
+ # theirs. A missing name silently degraded to "spine", which is the failure
576
+ # mode that has now cost this line two matrices.
577
+ #
578
+ # Ownership is therefore explicit and total: every trainable parameter must
579
+ # belong to exactly one group, and an unowned parameter ABORTS rather than
580
+ # being absorbed by whichever group happens to catch it.
581
+ groups: dict[str, list] = {
582
+ "compiler_symbols": [], # e_code, e_blank -- the symbol map
583
+ "compiler_reader": [], # E_byte, W_b, W_c -- byte -> symbol
584
+ "actions": [], # F_raw -- the semigroup
585
+ "carrier": [], # S -- readout carrier
586
+ "spine": [],
587
+ }
588
+ OWNERS = (
589
+ ("compiler_symbols", ("e_code", "e_blank")),
590
+ ("compiler_reader", ("E_byte", "W_b.weight", "W_c.weight")),
591
+ ("actions", ("F_raw",)),
592
+ ("carrier", ("field.S",)),
593
+ )
594
+ unowned = []
595
+ for n, p in model.named_parameters():
596
+ if not p.requires_grad:
597
+ continue
598
+ for group, suffixes in OWNERS:
599
+ if any(n == s or n.endswith("." + s) or n.endswith(s)
600
+ for s in suffixes):
601
+ groups[group].append((n, p))
602
+ break
603
+ else:
604
+ if n.startswith("spine."):
605
+ groups["spine"].append((n, p))
606
+ else:
607
+ unowned.append(n)
608
+ if unowned:
609
+ raise SystemExit(
610
+ "optimizer ownership is not exhaustive; these trainable tensors "
611
+ "belong to no declared group and would be clipped against "
612
+ f"whichever group caught them: {unowned}")
613
+ seen: dict[int, str] = {}
614
+ for gname, items in groups.items():
615
+ for n, p in items:
616
+ if id(p) in seen:
617
+ raise SystemExit(
618
+ f"parameter {n} is owned by both {seen[id(p)]} and {gname}")
619
+ seen[id(p)] = gname
620
+ if model.field is not None:
621
+ for gname in ("compiler_symbols", "compiler_reader", "actions",
622
+ "carrier"):
623
+ if not groups[gname]:
624
+ raise SystemExit(
625
+ f"group {gname} is empty while a field is present; the "
626
+ f"partition no longer matches the nucleus")
627
+ print("[opt] " + " ".join(
628
+ f"{g}={[n for n, _ in items]}" for g, items in groups.items()
629
+ if g != "spine"), flush=True)
630
+
631
+ comp = [p for _, p in groups["compiler_symbols"]]
632
+ reader = [p for _, p in groups["compiler_reader"]]
633
+ actions = [p for _, p in groups["actions"]]
634
+ carrier = [p for _, p in groups["carrier"]]
635
+ rest = [p for _, p in groups["spine"]]
636
+ # The code actions get NO weight decay. They are initialized at
637
+ # I + noise, and 0.01 decay over 24k updates at lr 1e-3 multiplies that
638
+ # identity component by exp(-0.24) = 0.787 -- the optimizer was quietly
639
+ # dismantling the very structure the oracle certifies, and the oracle
640
+ # itself runs decay-free, so the two were not even the same executor.
641
+ opt = torch.optim.AdamW(
642
+ [{"params": rest, "lr": LR},
643
+ {"params": comp, "lr": COMP_LR},
644
+ # the reader keeps the nominal LR: it was never meant to be slowed,
645
+ # only to be clipped on its own norm instead of the spine's
646
+ {"params": reader, "lr": LR},
647
+ {"params": carrier, "lr": LR},
648
+ {"params": actions, "lr": LR, "weight_decay": 0.0}],
649
+ weight_decay=0.01)
650
+ for g in opt.param_groups:
651
+ g["base_lr"] = g["lr"]
652
+ # Every declared group clips on its OWN norm. The reader and carrier were
653
+ # previously inside `spine` and therefore inside its ~3915 norm.
654
+ clip_groups = {"compiler_symbols": comp, "compiler_reader": reader,
655
+ "actions": actions, "carrier": carrier, "spine": rest}
656
+ clip_norms: Dict[str, float] = {}
657
+
658
+ rng = np.random.default_rng(3000 + seed)
659
+ # Evaluation must not share the training stream. It did: `evaluate` drew
660
+ # from `rng`, and a field arm draws extra binding and purity samples that
661
+ # NO-OPFIELD never draws, so the training bytes AFTER the first evaluation
662
+ # were not identical across arms -- a control-validity defect, and a
663
+ # confound for every mid-run swing, since a resampled panel makes
664
+ # evaluation noise look like training instability. The panel is now
665
+ # frozen once, domain-separated, and shared by every checkpoint and every
666
+ # matched control.
667
+ eval_rng = np.random.default_rng(0xE7A1_0000 + seed)
668
+ train_words = enumerate_words(0, TRAIN_DEPTH)
669
+ by_depth = {d: [w for w in train_words if len(w) == d]
670
+ for d in range(TRAIN_DEPTH + 1)}
671
+ cursor = {d: 0 for d in by_depth}
672
+ hist, t0 = [], time.time()
673
+
674
+ for step in range(STEPS):
675
+ frac = step / max(1, STEPS - 1)
676
+ lam_mid = (LAM_MID if MID_WARMUP <= 0
677
+ else LAM_MID * min(1.0, frac / MID_WARMUP))
678
+ cur_depth = (TRAIN_DEPTH if CURRIC <= 0 else
679
+ 1 + int((TRAIN_DEPTH - 1) * min(1.0, frac / CURRIC)))
680
+ st_now = ST or (ST_AFTER > 0 and frac >= ST_AFTER)
681
+ words, onehot, wlen, log_eps, log_floor, strata = alpha[cur_depth]
682
+ total = 0.0
683
+ bits = 0.0
684
+ for _ in range(EVENTS):
685
+ d = step % (cur_depth + 1)
686
+ pool = by_depth[d]
687
+ w = pool[cursor[d] % len(pool)]
688
+ cursor[d] += 1
689
+ rec = torch.from_numpy(
690
+ make_event(w, word_perm(perms, w), rng).astype(np.int64)
691
+ ).to(DEVICE)
692
+ pre, per_word, prior = event_codelength(
693
+ model, rec, words, onehot, wlen, salt=step, lam_mid=lam_mid,
694
+ st=st_now)
695
+ if model.field is None:
696
+ total = total + pre + per_word.sum()
697
+ bits = bits + float(pre) + float(per_word.sum())
698
+ continue
699
+ logpi = torch.log_softmax(prior, dim=-1)
700
+ mixed = torch.logaddexp(
701
+ logpi + math.log(1 - EPS),
702
+ log_floor if log_floor is not None
703
+ else torch.full_like(logpi, log_eps))
704
+ with torch.no_grad():
705
+ # beta-tempered posterior and the matching free energy.
706
+ #
707
+ # F_b = min_q [ E_q C_w + b * KL_2(q || pi_eps) ]
708
+ # = -b * log2 sum_w pi_eps(w) 2^(-C_w / b)
709
+ #
710
+ # Why this is needed: C_w sums 128 answer bytes, so an
711
+ # accidental advantage of 0.1 bit/byte is posterior odds of
712
+ # 2^12.8 ~ 7100. Over 2047 words the posterior is essentially
713
+ # one-hot on a RANDOM alias before any action has acquired
714
+ # meaning, and the run is then doing hard EM over aliases.
715
+ # Raising the rate price to b bits makes an alternative pay
716
+ # b*log2(W/eps) = 61.3 bits at b=4 before it can displace the
717
+ # incumbent, which random advantages should not clear while a
718
+ # correct action (saving ~998 bits) clears it easily.
719
+ #
720
+ # A0: C_w is L_post and the KL is R_A, both listed terms.
721
+ # b > 1 is a STRICTER rate charge than the minimum, never a
722
+ # weaker one, and the posterior stays training-only and
723
+ # equivariant under permutation of the codes.
724
+ q = torch.softmax(mixed - per_word * math.log(2.0) / BETA_A, -1)
725
+ # the honest codelength, always the exact marginal
726
+ code_bits = -torch.logsumexp(
727
+ mixed - per_word * math.log(2.0), dim=-1) / math.log(2.0)
728
+ if SAMPLED:
729
+ # EM M-step, sampled: E_q[C_w] has the same executor gradient
730
+ # as the marginal (q IS the posterior, so the envelope
731
+ # theorem applies) but the realized gradient runs through ONE
732
+ # word, so all M*8 answers in the event push a single coherent
733
+ # program. The full marginal instead pulls every action
734
+ # toward the posterior-mean word, which is not a word.
735
+ if STRATIFIED:
736
+ # STRATIFIED EM M-step. One draw from q almost always
737
+ # returns blank or a long word, so a primitive action can
738
+ # go thousands of steps with no coherent credit at all --
739
+ # and when the posterior sits on blank, the drawn word is
740
+ # the EMPTY one, which by a pinned nucleus invariant touches
741
+ # no action parameter, so the actions receive exactly zero
742
+ # gradient and the deadlock is permanent. Splitting the
743
+ # exact posterior by length and drawing one word per stratum
744
+ # guarantees a primitive gets a coherent update every event,
745
+ # while the composite stratum still contributes ONE coherent
746
+ # program rather than a posterior mean that is not a word.
747
+ #
748
+ # E[grad] = sum_j Q_j E_{w~q(.|S_j)}[grad C_w]
749
+ # = sum_w q(w) grad C_w
750
+ #
751
+ # i.e. the SAME L_post gradient, since q is detached. This
752
+ # is a variance-reduction of a listed term, not a new one.
753
+ exec_term = per_word.new_zeros(())
754
+ for mask in strata:
755
+ mass = float(q[mask].sum())
756
+ if mass <= 0.0:
757
+ continue
758
+ sub = q[mask] / mass
759
+ pick = int(torch.multinomial(sub, 1))
760
+ idx = int(mask.nonzero()[pick])
761
+ exec_term = exec_term + mass * per_word[idx]
762
+ else:
763
+ exec_term = per_word[int(torch.multinomial(q, 1))]
764
+ else:
765
+ # The compiler is trained ONLY by the mirror step below.
766
+ # Leaving the marginal attached to `prior` sent it a second,
767
+ # undeclared gradient on top of the mirror step.
768
+ exec_term = -torch.logsumexp(
769
+ mixed.detach() - per_word * math.log(2.0),
770
+ dim=-1) / math.log(2.0)
771
+ # base 2: the rest of this objective is bits, and log_softmax is
772
+ # natural log, so the mirror step was silently weighted by 1/ln2.
773
+ # Scaled by BETA_A so the mirror surrogate is the gradient of the
774
+ # same beta free energy the posterior above is drawn from, rather
775
+ # than of a different objective.
776
+ comp_loss = -BETA_A * (
777
+ q * torch.log_softmax(prior, -1)).sum() / math.log(2.0)
778
+ total = total + pre + exec_term + comp_loss
779
+ bits = bits + float(pre) + float(code_bits)
780
+ loss = total / max(1, EVENTS)
781
+ opt.zero_grad(set_to_none=True)
782
+ loss.backward()
783
+ if GROUP_CLIP:
784
+ # One global norm over compiler + actions + spine is positive
785
+ # feedback: the answer gradient sums 128 bytes through up to ten
786
+ # actions while the compiler gets a single mirror term, so the
787
+ # seed with the largest executor gradient receives the SMALLEST
788
+ # effective compiler update -- exactly the seed that needs the
789
+ # compiler to move. Seed 1 never left its initial basin.
790
+ # Clipping each group against its own norm removes the coupling.
791
+ # A0: a block-diagonal preconditioner carries no signal.
792
+ for gname, plist in clip_groups.items():
793
+ gs = [p for p in plist if p.grad is not None]
794
+ if gs:
795
+ n = torch.nn.utils.clip_grad_norm_(gs, 1.0)
796
+ clip_norms[gname] = float(n)
797
+ else:
798
+ clip_norms["global"] = float(torch.nn.utils.clip_grad_norm_(
799
+ [p for p in model.parameters() if p.requires_grad], 1.0))
800
+ # Linear warmup then cosine decay, applied to each group's own base LR.
801
+ # The completed 24k matrix ran with NO schedule at all -- a constant
802
+ # 1e-3 for the whole run -- and every field seed random-walked rather
803
+ # than converged: seed 0 reached 0.875 record-exact at 18k and fell to
804
+ # 0.625 by 24k. A constant step against a sharpening discrete
805
+ # posterior, with credit routed through one sampled word, cannot settle
806
+ # into a basin it has already found. Default is OFF so the registered
807
+ # matrix's law is reproduced exactly; COSINE=1 selects the new arm.
808
+ if COSINE:
809
+ if step < LR_WARMUP:
810
+ scale = (step + 1) / max(1, LR_WARMUP)
811
+ else:
812
+ p = (step - LR_WARMUP) / max(1, STEPS - LR_WARMUP)
813
+ scale = LR_FLOOR + (1 - LR_FLOOR) * 0.5 * (
814
+ 1 + math.cos(math.pi * min(1.0, p)))
815
+ for g in opt.param_groups:
816
+ g["lr"] = g["base_lr"] * scale
817
+ opt.step()
818
+
819
+ if step % EVAL_EVERY == 0 or step == STEPS - 1:
820
+ # a FRESH generator from the frozen seed every time, so each
821
+ # checkpoint is scored on the identical panel and the training
822
+ # stream is untouched
823
+ row = evaluate(model, perms,
824
+ np.random.default_rng(0xE7A1_0000 + seed)
825
+ if FROZEN_PANEL else rng)
826
+ row.update({f"clip_{k}": round(v, 3)
827
+ for k, v in clip_norms.items()})
828
+ row.update({"step": step, "loss": float(loss),
829
+ "train_bits": round(bits / max(1, EVENTS), 2),
830
+ "lam_mid": round(lam_mid, 4),
831
+ "cur_depth": cur_depth, "st": int(st_now),
832
+ "s_per_step": round(
833
+ (time.time() - t0) / max(1, step), 4),
834
+ "wall_s": round(time.time() - t0, 1)})
835
+ hist.append(row)
836
+ print(f"[{ARM}-s{seed}] {row}", flush=True)
837
+ out["history"] = hist
838
+ out["final"] = row
839
+ if on_progress is not None:
840
+ on_progress()
841
+
842
+ out["history"] = hist
843
+ out["final"] = hist[-1] if hist else {}
844
+ return out
845
+
846
+
847
+ @torch.no_grad()
848
+ def _run_event(model: FS16Probe, w: Tuple[int, ...], perm: np.ndarray,
849
+ rng: np.random.Generator
850
+ ) -> Tuple[float, float, float, Optional[Tuple[int, ...]]]:
851
+ """One event under the hard deploy law -> (byte acc, record exact,
852
+ answer bits/byte, the compiler's hard word)."""
853
+ xpos, ypos = target_positions()
854
+ rec = torch.from_numpy(
855
+ make_event(w, perm, rng).astype(np.int64)).to(DEVICE)
856
+ logits, states = model.spine_pass(rec)
857
+ x = rec[:, xpos].reshape(-1)
858
+ y = rec[:, ypos].reshape(-1)
859
+ ans = logits[:, ypos].reshape(-1, 256)
860
+ hard_w: Optional[Tuple[int, ...]] = None
861
+ if model.field is not None:
862
+ hard_w = model.field.argmax_word(
863
+ _slot_logits(model.field, rec, states))[0]
864
+ wl, _ = model.field.tree_execute(
865
+ x, sorted({hard_w[:i] for i in range(len(hard_w) + 1)},
866
+ key=len), model.base_decode, hard=True)
867
+ # the certified law's own logits REPLACE the spine readout; the
868
+ # no-field control keeps its contextual spine logits, so the control
869
+ # is scored on the strictly easier readout of the two
870
+ ans = wl[-1]
871
+ lp = torch.log_softmax(ans.float(), -1)
872
+ bits = float(-lp.gather(1, y.view(-1, 1)).mean() / math.log(2.0))
873
+ pred = ans.argmax(-1)
874
+ return (float(pred.eq(y).float().mean()),
875
+ float(pred.view(M_REC, N_PAIRS).eq(
876
+ y.view(M_REC, N_PAIRS)).all(1).float().mean()),
877
+ bits, hard_w)
878
+
879
+
880
+ @torch.no_grad()
881
+ def evaluate(model: FS16Probe, perms: List[np.ndarray],
882
+ rng: np.random.Generator) -> Dict[str, float]:
883
+ """The preregistered gate quantities, under the hard deploy law.
884
+
885
+ Held-out closure depths 11..16 are never trained. Each reading scores
886
+ EVAL_WORDS fresh words x EVAL_EVENTS events per depth, so it rests on
887
+ EVAL_WORDS*EVAL_EVENTS*M_REC*N_PAIRS answer bytes. The first cut used
888
+ ONE word and ONE event per depth — 384 bytes total — whose sampling
889
+ noise was large enough to swing the pilot's held-out accuracy between
890
+ 0.35 and 0.10 on consecutive readings. No gate can be scored off that.
891
+ """
892
+ row: Dict[str, float] = {}
893
+ accs, exact, bits = [], [], []
894
+ for d in range(TRAIN_DEPTH + 1, CLOSURE + 1):
895
+ da, de, db = [], [], []
896
+ for _ in range(EVAL_WORDS):
897
+ w = tuple(rng.integers(0, K_CODES, size=d).tolist())
898
+ perm = word_perm(perms, w)
899
+ for _ in range(EVAL_EVENTS_PER_WORD):
900
+ a, e, b, _ = _run_event(model, w, perm, rng)
901
+ da.append(a); de.append(e); db.append(b)
902
+ row[f"acc_d{d}"] = round(float(np.mean(da)), 4)
903
+ row[f"exact_d{d}"] = round(float(np.mean(de)), 4)
904
+ accs += da; exact += de; bits += db
905
+ row["heldout_byte_acc"] = float(np.mean(accs))
906
+ row["heldout_record_exact"] = float(np.mean(exact))
907
+ row["heldout_answer_bpb"] = float(np.mean(bits))
908
+ row["heldout_min_exact"] = min(row[f"exact_d{d}"] for d in
909
+ range(TRAIN_DEPTH + 1, CLOSURE + 1))
910
+ if model.field is None:
911
+ return row
912
+
913
+ # ---- binding gates: does the compiler read programs to codes? ----
914
+ votes: List[Dict[int, int]] = [{} for _ in range(K_CODES)]
915
+ len1: List[bool] = []
916
+ for g in range(K_CODES):
917
+ for _ in range(EVAL_BIND):
918
+ _, _, _, hw = _run_event(model, (g,), perms[g], rng)
919
+ len1.append(len(hw) == 1)
920
+ if len(hw) == 1:
921
+ votes[g][hw[0]] = votes[g].get(hw[0], 0) + 1
922
+ code_map = [max(v, key=v.get) if v else None for v in votes]
923
+ row["singleton_len1"] = float(np.mean(len1))
924
+ row["distinct_codes"] = float(
925
+ len({c for c in code_map if c is not None}) == K_CODES)
926
+ row["code_map"] = str(code_map)
927
+
928
+ ident = np.arange(256, dtype=np.uint8)
929
+ row["empty_word_rate"] = float(np.mean(
930
+ [len(_run_event(model, (), ident, rng)[3]) == 0
931
+ for _ in range(EVAL_BIND)]))
932
+
933
+ # word purity: the hard word must be the singleton mapping applied to
934
+ # the true program, at EVERY depth including the untrained closure
935
+ if all(c is not None for c in code_map):
936
+ pure, plen, per_depth = [], [], []
937
+ for d in range(0, CLOSURE + 1):
938
+ dp = []
939
+ for _ in range(EVAL_PURITY):
940
+ w = tuple(rng.integers(0, K_CODES, size=d).tolist())
941
+ _, _, _, hw = _run_event(model, w, word_perm(perms, w), rng)
942
+ dp.append(hw == tuple(code_map[g] for g in w))
943
+ plen.append(len(hw) == d)
944
+ pure += dp
945
+ per_depth.append(round(float(np.mean(dp)), 2))
946
+ row["word_purity"] = float(np.mean(pure))
947
+ row["word_len_match"] = float(np.mean(plen))
948
+ # aggregate purity cannot tell "perfect on the trained depths and
949
+ # failing on the untrained closure" apart from "uniformly mediocre",
950
+ # and those two call for different interventions
951
+ row["purity_by_depth"] = str(per_depth)
952
+ row["purity_trained"] = round(float(np.mean(
953
+ per_depth[:TRAIN_DEPTH + 1])), 3)
954
+ row["purity_closure"] = round(float(np.mean(
955
+ per_depth[TRAIN_DEPTH + 1:])), 3)
956
+ else:
957
+ row["word_purity"] = 0.0
958
+ row["word_len_match"] = 0.0
959
+ return row
960
+
961
+
962
+ def main() -> None:
963
+ nonce, perms = find_nonce(CLOSURE)
964
+ print(f"nonce={nonce} collision-free to depth {CLOSURE}", flush=True)
965
+ payload: Dict[str, object] = {
966
+ "screen": "G1-FS16", "arm": ARM, "seeds": SEEDS, "nonce": nonce,
967
+ "steps": STEPS, "events": EVENTS, "m_records": M_REC,
968
+ "d": D_MODEL, "layers": N_LAYERS, "carrier": CARRIER,
969
+ "train_depth": TRAIN_DEPTH, "closure": CLOSURE,
970
+ "lam_mid": LAM_MID, "lam_cpu": LAM_CPU, "lam_a": LAM_A,
971
+ "mid_warmup": MID_WARMUP, "curriculum": CURRIC, "straight_through": ST,
972
+ "st_after": ST_AFTER, "act_init": ACT_INIT, "sampled": SAMPLED,
973
+ "eps": EPS, "device": str(DEVICE), "runs": [], "partial": True,
974
+ "result_file": RESULT_FILE, "off_law": OFF_LAW,
975
+ "certification_geometry": not OFF_LAW,
976
+ }
977
+
978
+ def push() -> None:
979
+ # A local smoke run inherits HF_TOKEN from the shell, so without an
980
+ # explicit opt-out it publishes toy-width numbers over a registered
981
+ # result file under the DEFAULT name. That already happened once.
982
+ if not os.environ.get("HF_TOKEN") or NO_PUSH:
983
+ return
984
+ api = HfApi()
985
+ api.create_repo(RESULTS_REPO, repo_type="model", exist_ok=True)
986
+ api.upload_file(
987
+ path_or_fileobj=json.dumps(payload, indent=1).encode(),
988
+ path_in_repo=RESULT_FILE, repo_id=RESULTS_REPO,
989
+ repo_type="model")
990
+ print(f"pushed {RESULTS_REPO}/{RESULT_FILE}", flush=True)
991
+
992
+ for seed in SEEDS:
993
+ run: Dict[str, object] = {}
994
+ payload["runs"].append(run)
995
+ train_one(seed, perms, run, on_progress=push)
996
+ push()
997
+ payload["partial"] = False
998
+ push()
999
+ print(json.dumps({"arm": ARM,
1000
+ "runs": [r.get("final", r) for r in payload["runs"]]},
1001
+ indent=1), flush=True)
1002
+
1003
+
1004
+ if __name__ == "__main__":
1005
+ main()