AbstractPhil commited on
Commit
f4fc35b
·
verified ·
1 Parent(s): 13324b2

exp002_refine: the aleph-addressed patchwork consumer wins (13.997 mean, 2 seeds, first relay under 14); width/strobe saturated; coverage beats concentration (-0.48); wide MLP diverges 1/2 seeds vs 0% for all relays; ordering budget-stable at 6k

Browse files
exp002_refine/README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # exp002_refine — refining the relay: five prototypical enhancements
2
+
3
+ Experiment 2 of the geolip-aleph-qwen line. [exp001](../exp001_relay/) found
4
+ the retrofit works at 0.5B (−21% ppl at <0.6% trainable) but the matched MLP
5
+ adapter edges the bare relay on perplexity while the gate mechanism favors
6
+ the relay. exp002 races five prototypical relay enhancements — each grounded
7
+ in a law certified upstream — at an equalized wider budget (~230K/adapter,
8
+ ~5.5M total), against the wide-MLP capacity control. Training identical to
9
+ exp001 (frozen Qwen2.5-0.5B, wikitext-103, block 512, batch 4, 3000 steps,
10
+ pure Adam lr 1e-3 wd 0).
11
+
12
+ ## Results
13
+
14
+ | arm (per-adapter design) | s0 | s1 | verdict |
15
+ |---|---|---|---|
16
+ | relay32 (2× slot width) | 14.089 | 14.069 | width saturated (16-slot: 14.093/14.091) |
17
+ | relay_3tau (rule-of-3 strobe) | 14.112 | — | no lift on this substrate |
18
+ | **relay_pw (patchwork consumer)** | **13.982** | **14.012** | **winner — certified 2 seeds** |
19
+ | relay_deep (all budget, last 12 blocks) | 14.576 | — | coverage beats concentration (−0.48) |
20
+ | mlp_wide (hidden 128 control) | **NaN** | 13.930 | diverged 1/2 seeds; no gain over narrow |
21
+ | relay_pw @ 6000 steps | 13.983 | — | converged at 3k |
22
+ | mlp64 @ 6000 steps (companion) | 13.899 | — | still improving — ordering budget-stable |
23
+
24
+ References (exp001, certified): frozen 17.798; relay16 14.093/14.091; mlp64
25
+ 13.927/13.935. `build_results.py` re-asserts every claim from
26
+ `results/ledger.jsonl` (+ the mlp@6k companion row).
27
+
28
+ ## Findings
29
+
30
+ 1. **The aleph-addressed patchwork consumer is the refinement that works.**
31
+ Replacing the relay's bare linear output with the constellation
32
+ consumption spec — `M̂ → Linear(64,178) → SquaredReLU → LN → zero-init
33
+ Linear(178,896)` — beats the bare relay by ~0.09 ppl at both seeds
34
+ (13.997 mean vs 14.092): the first relay variant under 14. Addressing
35
+ stays aleph; consumption goes constellation.
36
+ 2. **Width and temperature are saturated dials**: doubling slots buys
37
+ +0.01–0.02; the 3-tau strobe buys nothing here (its certified win was a
38
+ co-trained byte-LM regime).
39
+ 3. **Coverage beats concentration**: putting exp001's entire adapter budget
40
+ on the last 12 blocks costs 0.48 ppl at equal parameters, even though
41
+ those deep relays run the hottest gates (0.094) — the depth-gradient law
42
+ describes where cultivation concentrates, not where adapters belong.
43
+ 4. **The stability asymmetry, quantified at 0.5B**: the wide zero-init MLP
44
+ diverged to NaN at one of two seeds (50%) and gained nothing over the
45
+ narrow MLP at the other; every sphere-normalized relay variant — all five,
46
+ all seeds — trained without aid (0% divergence).
47
+ 5. **The perplexity ordering is budget-stable** (1 seed at ship time):
48
+ relay_pw is fully converged by 3k steps (6k: +0.001) while the MLP keeps
49
+ improving (13.927 → 13.899) — free capacity holds a small, persistent ppl
50
+ edge on this well-trained substrate. Combined with exp001's
51
+ gate-vs-ppl dissociation, the relay's value at 0.5B is its **stability,
52
+ its opt-in mechanism, and its discrete addressable surface** — the levers
53
+ the next experiments (sign-code tap, frozen-keyer registry) are built on —
54
+ rather than raw perplexity.
55
+
56
+ Checkpoint note: `adapters/` holds the latest checkpoint per (arm, seed);
57
+ for relay_pw s0 that is the 6000-step version (the 3000-step run's ppl is
58
+ ledgered; its weights were superseded in place).
59
+
60
+ ## Files
61
+ - `qwen_exp002_refine.py` — the five variants (Relay3Tau, RelayPatchwork,
62
+ width/depth builders), wave runner, smoke (budget-equalization asserted).
63
+ - `qwen_exp001_relay.py` + `geolip_vitals.py` / `ar_differentiation_bed.py` /
64
+ `exp013_augmentation_bed.py` — this package's own harness copies. Standalone.
65
+ - `repro.py`, `build_results.py`, `results/ledger.jsonl` (9 rows) +
66
+ `results/companion_mlp6k.jsonl`, `adapters/` (8 checkpoints).
67
+
68
+ ## Reproduce (from inside this folder)
69
+ ```bash
70
+ pip install torch --index-url https://download.pytorch.org/whl/cu128
71
+ pip install transformers pyarrow huggingface_hub
72
+ python repro.py # CPU smoke
73
+ python repro.py --run # Wave A (GPU)
74
+ python repro.py --arm relay_pw --seed 1 --steps 6000 # any single cell
75
+ python build_results.py # re-assert every claim
76
+ ```
77
+ Data lands in `./data` (override with `GEOLIP_DATA`).
78
+
79
+ License: MIT · AbstractPhil + Claude Fable 5 · July 12, 2026
exp002_refine/adapters/q2_mlp_wide_s0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ab1522dc23cc11a697e6dd56ac77742ea0793e86ba1f30689694c1bc9d588fe
3
+ size 22153985
exp002_refine/adapters/q2_mlp_wide_s1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e294044aa04cb44708964d515082cdae47bca14721b0df95a39ccd4eb8d8328
3
+ size 22153985
exp002_refine/adapters/q2_relay32_s0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd86702a3f7aa5ca0002fb515fa7640777fdcede4505c66a71db0fa5b6f3e865
3
+ size 22104835
exp002_refine/adapters/q2_relay32_s1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c37b16a38b332209550cc0651c0bcebf867ae9b0c1fb64e3a63c7ebfed688f3f
3
+ size 22104835
exp002_refine/adapters/q2_relay_3tau_s0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1084ab623cb7e06610c967cc7daaa6a205a57449fac9f3cb746856a9892bba0
3
+ size 22105213
exp002_refine/adapters/q2_relay_deep_s0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d7d59ddfff2e1e42bd7dfa210d36ed2b4bf05dcf2521274c59a769b1371acc1
3
+ size 11052993
exp002_refine/adapters/q2_relay_pw_s0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:382da262682691a8e72bfc03d00381b8730a7d4e3653863bb90795a9173ef333
3
+ size 22166937
exp002_refine/adapters/q2_relay_pw_s1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dc19ea2ce67e369be4b2c5db1c04c3aec261337396cb34876548134e18f7559
3
+ size 22166937
exp002_refine/ar_differentiation_bed.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ar_differentiation_bed.py — exp012: autoregressive differentiation of the aleph.
2
+
3
+ Differentiation is cultivated by PREDICTIVE pressure along the sequence — the
4
+ address parameterizing the next-byte distribution (Law 2: chain-rule advantage pays
5
+ ONLY where the composed address directly parameterizes the predictive distribution).
6
+ This bed puts the aleph in the autoregressive gradient path and measures what
7
+ differentiates. The head arms enforce the employment law at its maximum: the
8
+ ENTIRE next-byte distribution is parameterized by the address.
9
+
10
+ Byte-level causal LM on wikitext-2-raw (HF parquet, CDN-fast), block 256. ARMS:
11
+ sdpa — standard causal transformer control (matched trunk).
12
+ hub — attention replaced by CAUSAL HUB: linear attention whose feature map
13
+ is the 2K-oriented aleph address, prefix-sum memories (no selection
14
+ event; O(n*K*d)). Differentiation cultivated INSIDE attention.
15
+ addr_head — sdpa trunk, but the OUTPUT HEAD reads ONLY the signed aleph
16
+ coefficient vector w_k = sinh(u_k)/sum_j cosh(u_j) of the final
17
+ hidden state (K -> 256 logits). The address MUST carry every bit of
18
+ next-byte information — the hardest Law-2 bottleneck.
19
+
20
+ JUDGED BY: val bits-per-byte per arm (task) + CULTIVATION VITALS on every aleph
21
+ codebook (readouts, never losses): axis aliveness/hppl, drift-from-init +
22
+ binding fraction @0.29154, winner-|cos| saturation (sign-code emergence), shadow
23
+ path diversity (fixed high-bits hash). Never by recon.
24
+
25
+ Riders: pure Adam wd=0; no BN/Dropout/GAP on geometric paths; orthogonal init;
26
+ Colab-cell-safe (paste-ahead imports, no bare argparse, no __file__ reliance);
27
+ GPU-only for verdict runs.
28
+
29
+ Terminal: python ar_differentiation_bed.py # shapes/parse smoke
30
+ python ar_differentiation_bed.py --train # verdict run
31
+ Colab: paste geolip_vitals.py cell, then this file (smoke auto-runs),
32
+ then train(steps=2000, data_root="/content/data") in the next cell.
33
+ """
34
+ from __future__ import annotations
35
+ import math
36
+ import torch
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+
40
+ if "anchor_drift" not in globals():
41
+ try:
42
+ from geolip_vitals import anchor_drift, axis_aliveness, path_diversity
43
+ except ImportError:
44
+ _here = globals().get("__file__")
45
+ if _here is not None:
46
+ import sys, pathlib
47
+ sys.path.insert(0, str(pathlib.Path(_here).parent))
48
+ from geolip_vitals import anchor_drift, axis_aliveness, path_diversity
49
+ else:
50
+ raise ImportError(
51
+ "geolip_vitals not found — paste/run its cell first, or "
52
+ "hf_hub_download exp012_ar/geolip_vitals.py from "
53
+ "AbstractPhil/geolip-aleph-differentiation.")
54
+
55
+ VOCAB = 256 # bytes
56
+
57
+
58
+ # ------------------------------------------------------------------ aleph address
59
+ def _super_fibonacci_s3(n: int) -> torch.Tensor:
60
+ """Near-uniform unit quaternions (Alexa CVPR'22) —
61
+ starts the codebook INSIDE the RP^3 attractor basin. D=4 only."""
62
+ PHI, PSI = math.sqrt(2.0), 1.533751168755204288118041
63
+ i = torch.arange(n, dtype=torch.float64)
64
+ s = (i + 0.5) / n
65
+ r, R = torch.sqrt(s), torch.sqrt(1.0 - s)
66
+ a, b = 2 * math.pi * i / PHI, 2 * math.pi * i / PSI
67
+ q = torch.stack([r * torch.sin(a), r * torch.cos(a),
68
+ R * torch.sin(b), R * torch.cos(b)], dim=-1)
69
+ return F.normalize(q, dim=-1).float()
70
+
71
+
72
+ class AlephAddress(nn.Module):
73
+ """Closed-form aleph over 2K oriented half-axes (aleph-void article).
74
+ signed(x): (..., K) w_k = sinh(u_k)/sum_j cosh(u_j) — the Law-2 head feature.
75
+ oriented(x): ((..., K), (..., K)) positive halves of the 2K softmax — HUB map."""
76
+
77
+ def __init__(self, K: int, D: int, tau: float = 0.1, init: str = "random"):
78
+ super().__init__()
79
+ self.K, self.D, self.tau = K, D, tau
80
+ if init == "fibonacci":
81
+ assert D == 4, "fibonacci init lives on S^3 (D=4)"
82
+ A = _super_fibonacci_s3(K)
83
+ else:
84
+ A = F.normalize(torch.randn(K, D), dim=-1)
85
+ self.codebook = nn.Parameter(A)
86
+ self.register_buffer("home", self.codebook.detach().clone())
87
+
88
+ def _u(self, x):
89
+ A = F.normalize(self.codebook, dim=-1)
90
+ return (F.normalize(x, dim=-1) @ A.transpose(-1, -2)) / self.tau
91
+
92
+ def oriented(self, x):
93
+ u = self._u(x)
94
+ m = u.abs().amax(dim=-1, keepdim=True)
95
+ ep, en = torch.exp(u - m), torch.exp(-u - m)
96
+ Z = (ep + en).sum(dim=-1, keepdim=True)
97
+ return ep / Z, en / Z
98
+
99
+ def signed(self, x):
100
+ u = self._u(x)
101
+ m = u.abs().amax(dim=-1, keepdim=True)
102
+ ep, en = torch.exp(u - m), torch.exp(-u - m)
103
+ return (ep - en) / (ep + en).sum(dim=-1, keepdim=True)
104
+
105
+ def signed_at(self, x, taus):
106
+ """Multi-tau stroboscope (rule of 3): signed coefficients at several
107
+ temperatures, concatenated — softer taus keep the vector dense while a
108
+ hard tau supplies the sign-code sharpness. v2 refinement (b)."""
109
+ A = F.normalize(self.codebook, dim=-1)
110
+ cos = F.normalize(x, dim=-1) @ A.transpose(-1, -2)
111
+ outs = []
112
+ for t in taus:
113
+ u = cos / t
114
+ m = u.abs().amax(dim=-1, keepdim=True)
115
+ ep, en = torch.exp(u - m), torch.exp(-u - m)
116
+ outs.append((ep - en) / (ep + en).sum(dim=-1, keepdim=True))
117
+ return torch.cat(outs, dim=-1)
118
+
119
+ def m_hat(self, x):
120
+ """Closed-form soft read (decoders read M_hat, never M). v2 control (c)."""
121
+ u = self._u(x)
122
+ m = u.abs().amax(dim=-1, keepdim=True)
123
+ ep, en = torch.exp(u - m), torch.exp(-u - m)
124
+ A = F.normalize(self.codebook, dim=-1)
125
+ return ((ep - en) @ A) / (ep + en).sum(dim=-1, keepdim=True)
126
+
127
+ def m_hard_ste(self, x):
128
+ """Hard mode (aleph-void article): M_hard = sign(cos_win) * A[win], straight-through to
129
+ the soft read — forward fully discrete SIGN CODE, backward soft gradient.
130
+ Legal per theme A (reconstructive sign code, not a one-hot roster pick)."""
131
+ u = self._u(x)
132
+ soft = self.m_hat(x)
133
+ win = u.abs().argmax(dim=-1)
134
+ A = F.normalize(self.codebook, dim=-1)
135
+ sign = torch.sign(torch.gather(u, -1, win.unsqueeze(-1))).squeeze(-1)
136
+ hard = sign.unsqueeze(-1) * A[win]
137
+ return hard + soft - soft.detach()
138
+
139
+ @torch.no_grad()
140
+ def vitals(self, x_sample) -> dict:
141
+ u = self._u(x_sample.reshape(-1, x_sample.shape[-1]))
142
+ p, n = self.oriented(x_sample.reshape(-1, x_sample.shape[-1]))
143
+ two_k = torch.cat([p, n], dim=-1)
144
+ win = two_k.argmax(dim=-1)
145
+ cos_win = (u.abs().amax(dim=-1) * self.tau) # winner |cos| — sign-code sat.
146
+ d = anchor_drift(self.codebook, self.home)
147
+ return {"drift": round(d["mean"], 4),
148
+ "binding_frac": round(d["binding_fraction"], 4),
149
+ "aliveness": axis_aliveness(two_k),
150
+ "win_cos_mean": round(cos_win.mean().item(), 4),
151
+ "paths": path_diversity(win)}
152
+
153
+
154
+ # ------------------------------------------------------------------------- blocks
155
+ class CausalSDPA(nn.Module):
156
+ def __init__(self, d: int, heads: int = 4):
157
+ super().__init__()
158
+ self.h = heads
159
+ self.qkv = nn.Linear(d, 3 * d, bias=False)
160
+ self.o = nn.Linear(d, d, bias=False)
161
+ nn.init.orthogonal_(self.qkv.weight); nn.init.orthogonal_(self.o.weight)
162
+
163
+ def forward(self, x):
164
+ B, n, d = x.shape
165
+ q, k, v = self.qkv(x).chunk(3, dim=-1)
166
+ q, k, v = (t.view(B, n, self.h, d // self.h).transpose(1, 2) for t in (q, k, v))
167
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
168
+ return self.o(y.transpose(1, 2).reshape(B, n, d))
169
+
170
+
171
+ class CausalHUB(nn.Module):
172
+ """Causal aleph linear attention: prefix-sum memories over the two K-wide
173
+ halves of the oriented address; 2K never materialized; no selection event."""
174
+
175
+ def __init__(self, d: int, K: int = 32, D: int = 4, tau: float = 0.1):
176
+ super().__init__()
177
+ self.addr = AlephAddress(K, D, tau)
178
+ self.q = nn.Linear(d, D, bias=False)
179
+ self.k = nn.Linear(d, D, bias=False)
180
+ self.v = nn.Linear(d, d, bias=False)
181
+ self.o = nn.Linear(d, d, bias=False)
182
+ for m in (self.q, self.k, self.v, self.o):
183
+ nn.init.orthogonal_(m.weight)
184
+
185
+ def forward(self, x):
186
+ qp, qn = self.addr.oriented(self.q(x)) # (B, n, K)
187
+ kp, kn = self.addr.oriented(self.k(x))
188
+ v = self.v(x) # (B, n, d)
189
+ Sp = torch.cumsum(torch.einsum("bnk,bnd->bnkd", kp, v), dim=1)
190
+ Sn = torch.cumsum(torch.einsum("bnk,bnd->bnkd", kn, v), dim=1)
191
+ zp = torch.cumsum(kp, dim=1)
192
+ zn = torch.cumsum(kn, dim=1)
193
+ num = torch.einsum("bnk,bnkd->bnd", qp, Sp) + torch.einsum("bnk,bnkd->bnd", qn, Sn)
194
+ den = (qp * zp).sum(-1, keepdim=True) + (qn * zn).sum(-1, keepdim=True)
195
+ return self.o(num / den.clamp_min(1e-12))
196
+
197
+
198
+ class MslRelay(nn.Module):
199
+ """Depth-composition unit (chain-rule probe): multi-slot M_hat read entering
200
+ the trunk as a NEAR-ZERO gated residual (gate init -3.0, sigma~0.047 — theme D:
201
+ geometry enters as a nudge and grows only if it earns gradient)."""
202
+
203
+ def __init__(self, d: int, n_slots: int = 16, K: int = 64):
204
+ super().__init__()
205
+ self.n_slots = n_slots
206
+ self.proj = nn.Linear(d, n_slots * 4, bias=False)
207
+ self.out = nn.Linear(n_slots * 4, d, bias=False)
208
+ nn.init.orthogonal_(self.proj.weight)
209
+ nn.init.orthogonal_(self.out.weight)
210
+ self.addr = AlephAddress(K, 4)
211
+ self.gate = nn.Parameter(torch.tensor(-3.0))
212
+
213
+ def forward(self, x):
214
+ B, n, _ = x.shape
215
+ slots = self.proj(x).view(B, n, self.n_slots, 4)
216
+ m = self.addr.m_hat(slots).reshape(B, n, -1)
217
+ return x + self.gate.sigmoid() * self.out(m)
218
+
219
+
220
+ class Block(nn.Module):
221
+ def __init__(self, d: int, attn: nn.Module):
222
+ super().__init__()
223
+ self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
224
+ self.attn = attn
225
+ self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
226
+
227
+ def forward(self, x):
228
+ x = x + self.attn(self.n1(x))
229
+ return x + self.mlp(self.n2(x))
230
+
231
+
232
+ class ByteLM(nn.Module):
233
+ def __init__(self, arm: str, d: int = 192, layers: int = 4, block: int = 256,
234
+ K: int = 32, D: int = 4):
235
+ super().__init__()
236
+ # "<arm>_tri" suffix = trigram byte embedding (AlephLM byte_emb x3 lineage):
237
+ # token embedding is the sum of embeddings of bytes t, t-1, t-2.
238
+ self.trigram = arm.endswith("_tri")
239
+ if self.trigram:
240
+ arm = arm[:-4]
241
+ # "_fib" = super-Fibonacci S^3 codebook init (basin test: starts INSIDE
242
+ # the RP^3 attractor; primary observable is init->final geodesic drift).
243
+ self.fib = arm.endswith("_fib")
244
+ if self.fib:
245
+ arm = arm[:-4]
246
+ # "relay*" = stacked addresses in depth: MslRelay after every block.
247
+ # relay -> sdpa trunk + standard head; relay_msl64 -> + addressed head.
248
+ self.use_relay = arm.startswith("relay")
249
+ if arm == "relay":
250
+ arm = "sdpa"
251
+ elif arm == "relay_msl64":
252
+ arm = "addr_msl64"
253
+ self.arm, self.block = arm, block
254
+ self.emb = nn.Embedding(VOCAB, d)
255
+ if self.trigram:
256
+ self.emb1 = nn.Embedding(VOCAB, d)
257
+ self.emb2 = nn.Embedding(VOCAB, d)
258
+ self.pos = nn.Parameter(torch.zeros(1, block, d) + 0.01 * torch.randn(1, block, d))
259
+ mk_attn = (lambda: CausalHUB(d, K, D)) if arm == "hub" else (lambda: CausalSDPA(d))
260
+ self.blocks = nn.ModuleList([Block(d, mk_attn()) for _ in range(layers)])
261
+ if self.use_relay:
262
+ self.relays = nn.ModuleList([MslRelay(d) for _ in range(layers)])
263
+ self.nf = nn.LayerNorm(d)
264
+ if arm == "addr_head":
265
+ self.head_addr = AlephAddress(K, d) # v1: codebook in model dim — COLLAPSED
266
+ self.head = nn.Linear(K, VOCAB, bias=True)
267
+ elif arm in ("addr_d4", "addr_3tau", "addr_mhat"):
268
+ # v2 refinements: LOW-D HOME — learned projection to the native D=4 home
269
+ # before addressing (mirrors the healthy HUB arms), K=64.
270
+ self.head_proj = nn.Linear(d, 4, bias=False)
271
+ nn.init.orthogonal_(self.head_proj.weight)
272
+ self.head_addr = AlephAddress(64, 4)
273
+ if arm == "addr_d4":
274
+ self.head = nn.Linear(64, VOCAB, bias=True) # w alone, D=4 home
275
+ elif arm == "addr_3tau":
276
+ self.taus = (0.05, 0.1, 0.3) # rule-of-3 strobe
277
+ self.head = nn.Linear(64 * 3, VOCAB, bias=True)
278
+ else: # addr_mhat
279
+ self.head = nn.Linear(4, VOCAB, bias=True) # tightest: M_hat
280
+ elif arm.startswith("addr_msl"):
281
+ # v3: MULTI-SLOT heads — the 16s funnel widening: P parallel D=4 slots
282
+ # over a SHARED codebook. addr_msl consumes the reconstructive M_hat per
283
+ # slot (Px4 dims); addr_msl_w consumes signed w per slot (Px64) — tests
284
+ # whether slot-parallel consumption alone rescues the coefficient path.
285
+ # addr_msl<P> = slot-count dose-response. addr_mslh<P> = HARD sign-code
286
+ # consumption (straight-through M_hard per slot).
287
+ self.hard = arm.startswith("addr_mslh")
288
+ if arm in ("addr_msl", "addr_msl_w"):
289
+ self.n_slots = 16
290
+ else:
291
+ self.n_slots = int(arm[len("addr_mslh" if self.hard else "addr_msl"):])
292
+ self.head_proj = nn.Linear(d, self.n_slots * 4, bias=False)
293
+ nn.init.orthogonal_(self.head_proj.weight)
294
+ self.head_addr = AlephAddress(
295
+ 64, 4, init="fibonacci" if self.fib else "random")
296
+ width = self.n_slots * (64 if arm == "addr_msl_w" else 4)
297
+ self.head = nn.Linear(width, VOCAB, bias=True)
298
+ elif arm == "addr_3tau_mhat":
299
+ # v3: combine the two v2 winners — 3-tau stroboscope + reconstructive read.
300
+ self.head_proj = nn.Linear(d, 4, bias=False)
301
+ nn.init.orthogonal_(self.head_proj.weight)
302
+ self.head_addr = AlephAddress(64, 4)
303
+ self.taus = (0.05, 0.1, 0.3)
304
+ self.head = nn.Linear(64 * 3 + 4, VOCAB, bias=True)
305
+ else:
306
+ self.head = nn.Linear(d, VOCAB, bias=True)
307
+ self._last_h = None
308
+
309
+ def forward(self, idx):
310
+ x = self.emb(idx)
311
+ if self.trigram: # past-only shifts — causality preserved
312
+ x = x + self.emb1(F.pad(idx, (1, 0), value=0)[:, :-1]) \
313
+ + self.emb2(F.pad(idx, (2, 0), value=0)[:, :-2])
314
+ x = x + self.pos[:, : idx.shape[1]]
315
+ if self.use_relay:
316
+ for b, r in zip(self.blocks, self.relays):
317
+ x = r(b(x))
318
+ else:
319
+ for b in self.blocks:
320
+ x = b(x)
321
+ h = self.nf(x)
322
+ self._last_h = h.detach()
323
+ if self.arm == "addr_head":
324
+ return self.head(self.head_addr.signed(h))
325
+ if self.arm == "addr_d4":
326
+ return self.head(self.head_addr.signed(self.head_proj(h)))
327
+ if self.arm == "addr_3tau":
328
+ return self.head(self.head_addr.signed_at(self.head_proj(h), self.taus))
329
+ if self.arm == "addr_mhat":
330
+ return self.head(self.head_addr.m_hat(self.head_proj(h)))
331
+ if self.arm.startswith("addr_msl"):
332
+ B, n, _ = h.shape
333
+ slots = self.head_proj(h).view(B, n, self.n_slots, 4)
334
+ if self.arm == "addr_msl_w":
335
+ feats = self.head_addr.signed(slots).reshape(B, n, -1)
336
+ elif getattr(self, "hard", False):
337
+ feats = self.head_addr.m_hard_ste(slots).reshape(B, n, -1)
338
+ else:
339
+ feats = self.head_addr.m_hat(slots).reshape(B, n, -1)
340
+ return self.head(feats)
341
+ if self.arm == "addr_3tau_mhat":
342
+ p = self.head_proj(h)
343
+ feats = torch.cat([self.head_addr.signed_at(p, self.taus),
344
+ self.head_addr.m_hat(p)], dim=-1)
345
+ return self.head(feats)
346
+ return self.head(h)
347
+
348
+ @torch.no_grad()
349
+ def vitals(self) -> dict:
350
+ out = {}
351
+ if self.arm == "hub":
352
+ for i, b in enumerate(self.blocks):
353
+ if self._last_h is not None:
354
+ out[f"L{i}"] = b.attn.addr.vitals(b.attn.q(self._last_h[:2]))
355
+ elif self.arm == "addr_head" and self._last_h is not None:
356
+ out["head"] = self.head_addr.vitals(self._last_h[:2])
357
+ elif self.arm in ("addr_d4", "addr_3tau", "addr_mhat",
358
+ "addr_3tau_mhat") and self._last_h is not None:
359
+ out["head"] = self.head_addr.vitals(self.head_proj(self._last_h[:2]))
360
+ elif self.arm.startswith("addr_msl") and self._last_h is not None:
361
+ slots = self.head_proj(self._last_h[:2])
362
+ out["head"] = self.head_addr.vitals(
363
+ slots.reshape(*slots.shape[:-1], self.n_slots, 4))
364
+ if self.use_relay and self._last_h is not None:
365
+ for i, r in enumerate(self.relays):
366
+ s = r.proj(self._last_h[:2])
367
+ v = r.addr.vitals(s.reshape(*s.shape[:-1], r.n_slots, 4))
368
+ out[f"relay{i}"] = {"gate": round(r.gate.sigmoid().item(), 4),
369
+ "drift": v["drift"],
370
+ "binding_frac": v["binding_frac"],
371
+ "ppl": round(v["aliveness"]["usage_ppl"], 1)}
372
+ return out
373
+
374
+
375
+ # --------------------------------------------------------------------------- data
376
+ def _wikitext_bytes(data_root: str):
377
+ """wikitext-2-raw as flat uint8 tensors via the HF parquet CDN."""
378
+ from huggingface_hub import hf_hub_download
379
+ import pyarrow.parquet as pq
380
+
381
+ def load(split):
382
+ p = hf_hub_download("Salesforce/wikitext",
383
+ f"wikitext-2-raw-v1/{split}-00000-of-00001.parquet",
384
+ repo_type="dataset", local_dir=data_root)
385
+ text = "".join(pq.read_table(p).column("text").to_pylist())
386
+ return torch.frombuffer(bytearray(text.encode("utf-8")), dtype=torch.uint8).clone()
387
+
388
+ return load("train"), load("validation")
389
+
390
+
391
+ def _batch(data: torch.Tensor, batch: int, block: int, device, g: torch.Generator):
392
+ ix = torch.randint(0, data.numel() - block - 1, (batch,), generator=g)
393
+ x = torch.stack([data[i:i + block] for i in ix]).long().to(device)
394
+ y = torch.stack([data[i + 1:i + block + 1] for i in ix]).long().to(device)
395
+ return x, y
396
+
397
+
398
+ # -------------------------------------------------------------------- train/smoke
399
+ def train(arms=("sdpa", "hub", "addr_head"), steps: int = 2000, batch: int = 32,
400
+ block: int = 256, device: str = "cuda", data_root: str = "./data",
401
+ seed: int = 0, eval_every: int = 500, save: bool = True):
402
+ """Verdict run — GPU only. Pure Adam wd=0. Reports val bits-per-byte + vitals.
403
+ save=True writes {data_root}/ar_ckpts/{arm}_s{seed}_t{steps}.pt per arm —
404
+ the cultivated codebooks are SPECIMENS for the projective reading instruments."""
405
+ import os
406
+ if device == "cuda" and not torch.cuda.is_available():
407
+ raise RuntimeError("Verdict runs are GPU-only (never CPU-train for accuracy).")
408
+ ckpt_dir = os.path.join(data_root, "ar_ckpts")
409
+ os.makedirs(ckpt_dir, exist_ok=True)
410
+ tr, va = _wikitext_bytes(data_root)
411
+ print(f"data ready: train {tr.numel():,} bytes, val {va.numel():,} bytes", flush=True)
412
+ results = {}
413
+ for arm in arms:
414
+ torch.manual_seed(seed)
415
+ g = torch.Generator().manual_seed(seed)
416
+ model = ByteLM(arm, block=block).to(device)
417
+ n_params = sum(p.numel() for p in model.parameters())
418
+ opt = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=0.0)
419
+ for step in range(1, steps + 1):
420
+ x, y = _batch(tr, batch, block, device, g)
421
+ logits = model(x)
422
+ loss = F.cross_entropy(logits.reshape(-1, VOCAB), y.reshape(-1))
423
+ opt.zero_grad(set_to_none=True)
424
+ loss.backward()
425
+ opt.step()
426
+ if step % eval_every == 0 or step == steps:
427
+ model.eval()
428
+ with torch.no_grad():
429
+ losses = []
430
+ for _ in range(20):
431
+ xv, yv = _batch(va, batch, block, device, g)
432
+ lv = F.cross_entropy(model(xv).reshape(-1, VOCAB),
433
+ yv.reshape(-1))
434
+ losses.append(lv.item())
435
+ bpb = sum(losses) / len(losses) / math.log(2)
436
+ print(f"[{arm}] step {step} val_bpb={bpb:.4f} vitals={model.vitals()}",
437
+ flush=True)
438
+ model.train()
439
+ results[arm] = {"val_bpb": bpb, "params": n_params, "vitals": model.vitals()}
440
+ if save:
441
+ path = os.path.join(ckpt_dir, f"{arm}_s{seed}_t{steps}.pt")
442
+ torch.save({"arm": arm, "seed": seed, "steps": steps, "val_bpb": bpb,
443
+ "state_dict": {k: v.cpu() for k, v in
444
+ model.state_dict().items()}}, path)
445
+ print(f"saved specimen: {path}", flush=True)
446
+ print(results, flush=True)
447
+ return results
448
+
449
+
450
+ def smoke():
451
+ """Shapes/parse only — no accuracy claims."""
452
+ x = torch.randint(0, VOCAB, (2, 64))
453
+ for arm in ("sdpa", "hub", "addr_head"):
454
+ m = ByteLM(arm, d=96, layers=2, block=64, K=16)
455
+ logits = m(x)
456
+ assert logits.shape == (2, 64, VOCAB)
457
+ logits.sum().backward()
458
+ # causality check: future byte must not affect past logits
459
+ with torch.no_grad():
460
+ a = m(x)[0, 10]
461
+ x2 = x.clone(); x2[0, 40] = (x2[0, 40] + 7) % 256
462
+ b = m(x2)[0, 10]
463
+ assert torch.allclose(a, b, atol=1e-4), f"{arm} leaks future context"
464
+ print(f"{arm}: OK params={sum(p.numel() for p in m.parameters()):,} "
465
+ f"vitals={m.vitals()}", flush=True)
466
+ print("OK — AR bed smoke passed (verdict run: train() on GPU)", flush=True)
467
+
468
+
469
+ def _in_notebook() -> bool:
470
+ try:
471
+ get_ipython() # type: ignore[name-defined] # noqa: F821
472
+ return True
473
+ except NameError:
474
+ return False
475
+
476
+
477
+ if __name__ == "__main__":
478
+ if _in_notebook():
479
+ smoke()
480
+ print("Notebook mode: call train(steps=2000) in the next cell (GPU).")
481
+ else:
482
+ import argparse
483
+ ap = argparse.ArgumentParser()
484
+ ap.add_argument("--train", action="store_true")
485
+ ap.add_argument("--steps", type=int, default=2000)
486
+ a, _ = ap.parse_known_args()
487
+ train(steps=a.steps) if a.train else smoke()
exp002_refine/build_results.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """build_results.py — exp002_refine: read results/ledger.jsonl (+ the mlp@6k
2
+ companion row from exp001's bed) and RE-ASSERT every claim in the README.
3
+ Run from inside this folder: python build_results.py
4
+ """
5
+ import json
6
+ import math
7
+ import os
8
+
9
+ HERE = os.path.dirname(os.path.abspath(__file__))
10
+ rows = [json.loads(l) for l in
11
+ open(os.path.join(HERE, "results", "ledger.jsonl"), encoding="utf-8")]
12
+ comp = [json.loads(l) for l in
13
+ open(os.path.join(HERE, "results", "companion_mlp6k.jsonl"),
14
+ encoding="utf-8")]
15
+ assert all(r["exp"] == "q2" for r in rows) and len(rows) == 9
16
+ assert len(comp) == 1 and comp[0]["steps"] == 6000
17
+
18
+ def cell(arm, seed, steps=3000):
19
+ return next(r for r in rows if r["arm"] == arm and r["seed"] == seed
20
+ and r["steps"] == steps)
21
+
22
+ # exp001 references (certified there): relay16 14.093/14.091, mlp64
23
+ # 13.927/13.935, frozen 17.798
24
+ REF_RELAY, REF_MLP = 14.092, 13.931
25
+
26
+ # claim 1: relay_pw is the certified best relay variant — under the bare relay
27
+ # by ~0.08 or more at BOTH seeds, and the only variant to beat it at all
28
+ for s, ref in ((0, 14.093), (1, 14.091)):
29
+ assert cell("relay_pw", s)["ppl"] <= ref - 0.075, s
30
+ assert cell("relay32", 0)["ppl"] > 13.99 and cell("relay32", 1)["ppl"] > 13.99
31
+ assert cell("relay_3tau", 0)["ppl"] > 14.09
32
+ assert cell("relay_deep", 0)["ppl"] > 14.5 # coverage beats concentration
33
+
34
+ # claim 2: width saturation — relay32 within 0.03 of the 16-slot relay
35
+ assert abs(cell("relay32", 0)["ppl"] - 14.093) < 0.03
36
+ assert abs(cell("relay32", 1)["ppl"] - 14.091) < 0.03
37
+
38
+ # claim 3: the stability asymmetry — mlp_wide diverged at one of two seeds
39
+ # (NaN), landed at narrow-MLP level at the other; relays never diverged
40
+ mw = [cell("mlp_wide", s)["ppl"] for s in (0, 1)]
41
+ assert sum(1 for p in mw if math.isnan(p)) == 1, mw
42
+ assert any(abs(p - REF_MLP) < 0.01 for p in mw if not math.isnan(p))
43
+ assert all(not math.isnan(r["ppl"]) for r in rows if r["arm"] != "mlp_wide")
44
+
45
+ # claim 4 (budget, 1 seed at ship time): relay_pw is converged at 3k
46
+ # (6k within 0.005) while the mlp still improves at 6k — ordering budget-stable
47
+ assert abs(cell("relay_pw", 0, 6000)["ppl"] - cell("relay_pw", 0)["ppl"]) < 0.005
48
+ assert comp[0]["ppl"] < REF_MLP
49
+
50
+ out = {"ppl": {f'{r["arm"]}_s{r["seed"]}_t{r["steps"]}': r["ppl"] for r in rows},
51
+ "companion_mlp6k": comp[0]["ppl"], "n_rows": len(rows) + 1}
52
+ json.dump(out, open(os.path.join(HERE, "results", "results.json"), "w",
53
+ encoding="utf-8"), indent=1)
54
+ print(f"{len(rows)}+1 rows -> results/results.json")
55
+ print("all README claims asserted OK")
exp002_refine/exp013_augmentation_bed.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """exp013_augmentation_bed.py — augmenting pretrained models with the aleph.
2
+ Three tracks, one file (sequel to exp012's ar_differentiation_bed):
3
+
4
+ A. AUTOREGRESSION FROM CLIP-L: next-token prediction over CLIP-tokenized text,
5
+ reading FROZEN openai/clip-vit-large-patch14 text-tower hidden states.
6
+ FACTOR: extraction layer in {final, penultimate} (the last two layers — the
7
+ penultimate is what diffusion stacks consume). Heads at ~matched params:
8
+ linear | mlp | aleph multi-slot M_hat (P=64, D=4, shared K=64 — the exp012
9
+ certified construction) | sign-code (straight-through).
10
+ B. JOINT-FAILURE PROBES on frozen pooled embeddings (CLIP-L both layers + BERT):
11
+ b1 SPELLING-AR — decode a word's characters from ONLY the head's read of its
12
+ pooled embedding (GATE: linear/mlp must fail <50% exact first);
13
+ b2 ORDER — original-vs-shuffled discrimination (secondary; info may be absent).
14
+ C. GPT-2 (124M) AUGMENTATION: frozen trunk + trainable adapters after every block —
15
+ aleph MslRelay adapters vs param-matched MLP adapters vs frozen baseline;
16
+ gate growth by depth is a first-class readout (exp012 depth-gradient law).
17
+
18
+ Riders: pure Adam wd=0; no contrastive/InfoNCE into address paths; vitals are
19
+ readouts; GPU-only for verdict runs; caches/specimens live OUTSIDE the repo.
20
+ Colab: paste geolip_vitals.py, then ar_differentiation_bed.py, then this file.
21
+ """
22
+ from __future__ import annotations
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ # ---- paste-ahead imports (notebook-safe) -----------------------------------------
32
+ if "anchor_drift" not in globals():
33
+ try:
34
+ from geolip_vitals import anchor_drift, axis_aliveness, path_diversity
35
+ except ImportError:
36
+ _here = globals().get("__file__")
37
+ if _here is None:
38
+ raise ImportError("paste/run geolip_vitals.py first")
39
+ import sys, pathlib
40
+ sys.path.insert(0, str(pathlib.Path(_here).parent))
41
+ from geolip_vitals import anchor_drift, axis_aliveness, path_diversity
42
+ if "AlephAddress" not in globals():
43
+ try:
44
+ from ar_differentiation_bed import AlephAddress, MslRelay, _wikitext_bytes
45
+ except ImportError:
46
+ _here = globals().get("__file__")
47
+ if _here is None:
48
+ raise ImportError("paste/run ar_differentiation_bed.py first")
49
+ from ar_differentiation_bed import AlephAddress, MslRelay, _wikitext_bytes
50
+
51
+ DATA_ROOT = os.environ.get("GEOLIP_DATA", "./data")
52
+
53
+
54
+ class SquaredReLU(nn.Module):
55
+ def forward(self, x):
56
+ return F.relu(x) ** 2
57
+
58
+
59
+ # =============================================================== head arm family ==
60
+ class HeadArm(nn.Module):
61
+ """Conditioning transform d_in -> F_OUT (256), then a shared-shape task head.
62
+ Arms: linear | mlp | aleph (multi-slot M_hat) | sign (straight-through M_hard).
63
+ The aleph arms are the exp012-certified construction: P=64 slots x D=4 over one
64
+ shared K=64 codebook."""
65
+ F_OUT = 256
66
+
67
+ def __init__(self, arm: str, d_in: int, mlp_hidden: int = 192):
68
+ # mlp_hidden=192 param-matches the aleph arm at d_in=768:
69
+ # mlp ~ 192*(768+256)+LN ~ 197K vs aleph proj 768*256 + codebook = 196.9K
70
+ super().__init__()
71
+ self.arm = arm
72
+ if arm == "linear":
73
+ self.net = nn.Linear(d_in, self.F_OUT, bias=False)
74
+ elif arm == "mlp":
75
+ self.net = nn.Sequential(nn.Linear(d_in, mlp_hidden), SquaredReLU(),
76
+ nn.LayerNorm(mlp_hidden),
77
+ nn.Linear(mlp_hidden, self.F_OUT))
78
+ elif arm in ("aleph", "sign"):
79
+ self.proj = nn.Linear(d_in, 64 * 4, bias=False)
80
+ nn.init.orthogonal_(self.proj.weight)
81
+ self.addr = AlephAddress(64, 4)
82
+ else:
83
+ raise ValueError(arm)
84
+
85
+ def forward(self, x):
86
+ if self.arm in ("linear", "mlp"):
87
+ return self.net(x)
88
+ slots = self.proj(x).reshape(*x.shape[:-1], 64, 4)
89
+ read = self.addr.m_hard_ste(slots) if self.arm == "sign" \
90
+ else self.addr.m_hat(slots)
91
+ return read.reshape(*x.shape[:-1], 256)
92
+
93
+ @torch.no_grad()
94
+ def vitals(self, x_sample) -> dict:
95
+ if self.arm in ("linear", "mlp"):
96
+ return {}
97
+ slots = self.proj(x_sample).reshape(*x_sample.shape[:-1], 64, 4)
98
+ p, n = self.addr.oriented(slots)
99
+ two_k = torch.cat([p, n], -1).reshape(-1, 128)
100
+ d = anchor_drift(self.addr.codebook, self.addr.home)
101
+ return {"drift": round(d["mean"], 4),
102
+ "binding_frac": round(d["binding_fraction"], 4),
103
+ "usage_ppl": round(axis_aliveness(two_k)["usage_ppl"], 1),
104
+ "paths": path_diversity(two_k.argmax(-1))["unique_hashed"]}
105
+
106
+ def param_count(self):
107
+ return sum(p.numel() for p in self.parameters())
108
+
109
+
110
+ # ================================================================== caches ========
111
+ def _wikitext_lines(data_root, min_chars=40, max_lines=None):
112
+ from huggingface_hub import hf_hub_download
113
+ import pyarrow.parquet as pq
114
+ out = {}
115
+ for split, cap in (("train", max_lines), ("validation", None)):
116
+ p = hf_hub_download("Salesforce/wikitext",
117
+ f"wikitext-2-raw-v1/{split}-00000-of-00001.parquet",
118
+ repo_type="dataset", local_dir=data_root)
119
+ lines = [t.strip() for t in pq.read_table(p).column("text").to_pylist()
120
+ if len(t.strip()) >= min_chars]
121
+ out[split] = lines[:cap] if cap else lines
122
+ return out["train"], out["validation"]
123
+
124
+
125
+ @torch.no_grad()
126
+ def cache_clip(data_root, n_train=12000, n_val=1500, device="cuda", batch=64):
127
+ """CLIP-L text tower over wikitext lines; caches BOTH of the last two layers.
128
+ hidden_states[-1] == the final encoder layer output (pre final-LN),
129
+ last_hidden_state == final-LN(final layer). We cache:
130
+ 'final' = last_hidden_state (what the projection head consumes),
131
+ 'penult' = hidden_states[-2] (the layer diffusion stacks consume).
132
+ Also caches pooled (EOS-position) vectors for both layers, and token ids."""
133
+ from transformers import CLIPTextModel, CLIPTokenizerFast
134
+ path = os.path.join(data_root, "exp013", "clip_cache.pt")
135
+ if os.path.exists(path):
136
+ return torch.load(path, map_location="cpu", weights_only=True)
137
+ os.makedirs(os.path.dirname(path), exist_ok=True)
138
+ tok = CLIPTokenizerFast.from_pretrained("openai/clip-vit-large-patch14")
139
+ model = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(device).eval()
140
+ tr_lines, va_lines = _wikitext_lines(data_root, max_lines=n_train)
141
+ va_lines = va_lines[:n_val]
142
+ def encode(lines):
143
+ H_f, H_p, IDS, EOS = [], [], [], []
144
+ for i in range(0, len(lines), batch):
145
+ enc = tok(lines[i:i + batch], padding="max_length", truncation=True,
146
+ max_length=77, return_tensors="pt").to(device)
147
+ out = model(**enc, output_hidden_states=True)
148
+ H_f.append(out.last_hidden_state.half().cpu())
149
+ H_p.append(out.hidden_states[-2].half().cpu())
150
+ IDS.append(enc.input_ids.cpu())
151
+ EOS.append(enc.input_ids.argmax(-1).cpu()) # EOT id is the max token id
152
+ return (torch.cat(H_f), torch.cat(H_p), torch.cat(IDS), torch.cat(EOS))
153
+ tr = encode(tr_lines)
154
+ va = encode(va_lines)
155
+ blob = {"train": {"final": tr[0], "penult": tr[1], "ids": tr[2], "eos": tr[3]},
156
+ "val": {"final": va[0], "penult": va[1], "ids": va[2], "eos": va[3]},
157
+ "vocab": tok.vocab_size}
158
+ torch.save(blob, path)
159
+ print(f"clip cache: train {tr[0].shape}, val {va[0].shape} -> {path}", flush=True)
160
+ return blob
161
+
162
+
163
+ @torch.no_grad()
164
+ def cache_word_embeddings(data_root, n_words=10000, device="cuda", batch=256):
165
+ """Pooled embeddings of frequent wikitext words for the spelling probe:
166
+ CLIP-L final + penultimate (EOS-pooled) and BERT (CLS + mean of last layer)."""
167
+ from transformers import (CLIPTextModel, CLIPTokenizerFast,
168
+ BertModel, BertTokenizerFast)
169
+ path = os.path.join(data_root, "exp013", "word_cache.pt")
170
+ if os.path.exists(path):
171
+ return torch.load(path, map_location="cpu", weights_only=True)
172
+ os.makedirs(os.path.dirname(path), exist_ok=True)
173
+ tr_lines, _ = _wikitext_lines(data_root)
174
+ from collections import Counter
175
+ cnt = Counter(w for l in tr_lines for w in re.findall(r"[a-z]{3,12}", l.lower()))
176
+ words = [w for w, _ in cnt.most_common(n_words)]
177
+ blob = {"words": words}
178
+ ct = CLIPTokenizerFast.from_pretrained("openai/clip-vit-large-patch14")
179
+ cm = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(device).eval()
180
+ fin, pen = [], []
181
+ for i in range(0, len(words), batch):
182
+ enc = ct(words[i:i + batch], padding="max_length", truncation=True,
183
+ max_length=77, return_tensors="pt").to(device)
184
+ out = cm(**enc, output_hidden_states=True)
185
+ eos = enc.input_ids.argmax(-1)
186
+ idx = torch.arange(eos.numel(), device=device)
187
+ fin.append(out.last_hidden_state[idx, eos].half().cpu())
188
+ pen.append(out.hidden_states[-2][idx, eos].half().cpu())
189
+ blob["clip_final"], blob["clip_penult"] = torch.cat(fin), torch.cat(pen)
190
+ del cm
191
+ bt = BertTokenizerFast.from_pretrained("bert-base-uncased")
192
+ bm = BertModel.from_pretrained("bert-base-uncased").to(device).eval()
193
+ cls, mean = [], []
194
+ for i in range(0, len(words), batch):
195
+ enc = bt(words[i:i + batch], padding=True, truncation=True,
196
+ max_length=16, return_tensors="pt").to(device)
197
+ out = bm(**enc).last_hidden_state
198
+ m = enc.attention_mask.unsqueeze(-1)
199
+ cls.append(out[:, 0].half().cpu())
200
+ mean.append(((out * m).sum(1) / m.sum(1)).half().cpu())
201
+ blob["bert_cls"], blob["bert_mean"] = torch.cat(cls), torch.cat(mean)
202
+ torch.save(blob, path)
203
+ print(f"word cache: {len(words)} words -> {path}", flush=True)
204
+ return blob
205
+
206
+
207
+ # ============================================================ track A =============
208
+ def track_a(arms=("linear", "mlp", "aleph", "sign"), layers=("final", "penult"),
209
+ steps=1500, batch=64, seed=0, device="cuda",
210
+ data_root=DATA_ROOT, eval_every=500, save=True):
211
+ """Next-CLIP-token prediction from frozen CLIP-L hidden states."""
212
+ if not torch.cuda.is_available():
213
+ raise RuntimeError("verdict runs are GPU-only")
214
+ blob = cache_clip(data_root, device=device)
215
+ V = blob["vocab"]
216
+ results = {}
217
+ ck_dir = os.path.join(data_root, "exp013", "ckpts")
218
+ os.makedirs(ck_dir, exist_ok=True)
219
+ for layer in layers:
220
+ Htr = blob["train"][layer].float()
221
+ ids_tr = blob["train"]["ids"]
222
+ Hva = blob["val"][layer].float()
223
+ ids_va = blob["val"]["ids"]
224
+ for arm in arms:
225
+ torch.manual_seed(seed)
226
+ g = torch.Generator().manual_seed(seed)
227
+ head = HeadArm(arm, Htr.shape[-1]).to(device)
228
+ out_proj = nn.Linear(HeadArm.F_OUT, V).to(device)
229
+ params = list(head.parameters()) + list(out_proj.parameters())
230
+ opt = torch.optim.Adam(params, lr=3e-4, weight_decay=0.0)
231
+ n_par = sum(p.numel() for p in params)
232
+ for step in range(1, steps + 1):
233
+ ix = torch.randint(0, Htr.shape[0], (batch,), generator=g)
234
+ h = Htr[ix].to(device)
235
+ y = ids_tr[ix].to(device)
236
+ logits = out_proj(head(h[:, :-1]))
237
+ loss = F.cross_entropy(logits.reshape(-1, V), y[:, 1:].reshape(-1))
238
+ opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
239
+ if step % eval_every == 0 or step == steps:
240
+ with torch.no_grad():
241
+ ls = []
242
+ for j in range(0, min(1024, Hva.shape[0]), batch):
243
+ h = Hva[j:j + batch].to(device)
244
+ y = ids_va[j:j + batch].to(device)
245
+ lg = out_proj(head(h[:, :-1]))
246
+ ls.append(F.cross_entropy(
247
+ lg.reshape(-1, V), y[:, 1:].reshape(-1)).item())
248
+ ce = sum(ls) / len(ls)
249
+ vit = head.vitals(Hva[:2, :8].to(device))
250
+ print(f"[A {layer} {arm} s{seed}] step {step} val_ce={ce:.4f} "
251
+ f"params={n_par:,} vitals={vit}", flush=True)
252
+ results[f"{layer}/{arm}/s{seed}"] = {"val_ce": ce, "params": n_par,
253
+ "vitals": vit}
254
+ if save and arm in ("aleph", "sign"):
255
+ torch.save({"track": "A", "layer": layer, "arm": arm, "seed": seed,
256
+ "val_ce": ce, "state_dict": {k: v.cpu() for k, v in
257
+ head.state_dict().items()}},
258
+ os.path.join(ck_dir, f"A_{layer}_{arm}_s{seed}.pt"))
259
+ print(results, flush=True)
260
+ return results
261
+
262
+
263
+ # ============================================================ track B =============
264
+ class CharDecoder(nn.Module):
265
+ """Tiny GRU char decoder conditioned ONLY on the arm's 256-d read."""
266
+ CHARS = "abcdefghijklmnopqrstuvwxyz"
267
+ def __init__(self, cond_dim=256, hidden=256):
268
+ super().__init__()
269
+ self.V = len(self.CHARS) + 2 # +BOS +EOS
270
+ self.emb = nn.Embedding(self.V, 64)
271
+ self.init = nn.Linear(cond_dim, hidden)
272
+ self.gru = nn.GRU(64, hidden, batch_first=True)
273
+ self.out = nn.Linear(hidden, self.V)
274
+
275
+ def encode_word(self, w):
276
+ return [1] + [2 + self.CHARS.index(c) for c in w] + [0] # BOS..EOS(0)
277
+
278
+ def forward(self, cond, tgt): # tgt: (B, L) int, teacher-forced
279
+ h0 = torch.tanh(self.init(cond)).unsqueeze(0)
280
+ x = self.emb(tgt[:, :-1])
281
+ y, _ = self.gru(x, h0)
282
+ return self.out(y) # predict tgt[:,1:]
283
+
284
+ @torch.no_grad()
285
+ def greedy(self, cond, max_len=14):
286
+ B = cond.shape[0]
287
+ h = torch.tanh(self.init(cond)).unsqueeze(0)
288
+ t = torch.ones(B, 1, dtype=torch.long, device=cond.device)
289
+ done = torch.zeros(B, dtype=torch.bool, device=cond.device)
290
+ outs = []
291
+ for _ in range(max_len):
292
+ y, h = self.gru(self.emb(t), h)
293
+ t = self.out(y).argmax(-1)
294
+ outs.append(t)
295
+ done |= (t.squeeze(1) == 0)
296
+ if done.all():
297
+ break
298
+ return torch.cat(outs, 1)
299
+
300
+
301
+ def track_b1(arms=("linear", "mlp"), substrates=("clip_final", "clip_penult",
302
+ "bert_cls", "bert_mean"), steps=3000, batch=128, seed=0,
303
+ device="cuda", data_root=DATA_ROOT, save=True):
304
+ """Spelling-AR from pooled embeddings. Run baselines first (the GATE:
305
+ qualify the task only if linear/mlp exact-match < 0.50), then aleph/sign."""
306
+ if not torch.cuda.is_available():
307
+ raise RuntimeError("verdict runs are GPU-only")
308
+ blob = cache_word_embeddings(data_root, device=device)
309
+ words = blob["words"]
310
+ dec_tpl = CharDecoder()
311
+ enc = [dec_tpl.encode_word(w) for w in words]
312
+ L = max(len(e) for e in enc)
313
+ tgt = torch.zeros(len(enc), L, dtype=torch.long)
314
+ for i, e in enumerate(enc):
315
+ tgt[i, :len(e)] = torch.tensor(e)
316
+ g0 = torch.Generator().manual_seed(1234) # fixed split across arms
317
+ perm = torch.randperm(len(words), generator=g0)
318
+ tr_ix, va_ix = perm[:9000], perm[9000:]
319
+ ck_dir = os.path.join(data_root, "exp013", "ckpts")
320
+ os.makedirs(ck_dir, exist_ok=True)
321
+ results = {}
322
+ for sub in substrates:
323
+ E = blob[sub].float()
324
+ for arm in arms:
325
+ torch.manual_seed(seed)
326
+ g = torch.Generator().manual_seed(seed)
327
+ head = HeadArm(arm, E.shape[-1]).to(device)
328
+ dec = CharDecoder().to(device)
329
+ params = list(head.parameters()) + list(dec.parameters())
330
+ opt = torch.optim.Adam(params, lr=1e-3, weight_decay=0.0)
331
+ for step in range(1, steps + 1):
332
+ ix = tr_ix[torch.randint(0, tr_ix.numel(), (batch,), generator=g)]
333
+ cond = head(E[ix].to(device))
334
+ t = tgt[ix].to(device)
335
+ lg = dec(cond, t)
336
+ mask = (t[:, 1:] != 0) | (torch.cumsum(t[:, 1:] == 0, 1) == 1)
337
+ loss = F.cross_entropy(lg[mask], t[:, 1:][mask])
338
+ opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
339
+ with torch.no_grad():
340
+ cond = head(E[va_ix].to(device))
341
+ pred = dec.greedy(cond)
342
+ t = tgt[va_ix, 1:].to(device)
343
+ n = min(pred.shape[1], t.shape[1])
344
+ pad_ok = torch.ones_like(t[:, :n], dtype=torch.bool)
345
+ seen_eos = torch.cumsum(t[:, :n] == 0, 1) > 0
346
+ match = ((pred[:, :n] == t[:, :n]) | seen_eos).all(-1)
347
+ exact = match.float().mean().item()
348
+ vit = head.vitals(E[va_ix[:16]].to(device))
349
+ print(f"[B1 {sub} {arm} s{seed}] exact={exact:.4f} vitals={vit}", flush=True)
350
+ results[f"{sub}/{arm}/s{seed}"] = {"exact": exact, "vitals": vit}
351
+ if save and arm in ("aleph", "sign"):
352
+ torch.save({"track": "B1", "sub": sub, "arm": arm, "seed": seed,
353
+ "exact": exact, "state_dict": {k: v.cpu() for k, v in
354
+ head.state_dict().items()}},
355
+ os.path.join(ck_dir, f"B1_{sub}_{arm}_s{seed}.pt"))
356
+ print(results, flush=True)
357
+ return results
358
+
359
+
360
+ # ============================================================ track C =============
361
+ class MLPAdapter(nn.Module):
362
+ """Param-matched plain adapter (the ablation twin of MslRelay).
363
+ hidden=64 matches MslRelay at d=768 (2*768*64=98.3K vs 98.6K incl codebook).
364
+ Output layer ZERO-INIT (standard adapter stabilization — the first version
365
+ diverged at lr 1e-3 with random init; the aleph relay needed no such aid,
366
+ which is itself a datapoint, but the control gets its best shot)."""
367
+ def __init__(self, d, hidden=64):
368
+ super().__init__()
369
+ out = nn.Linear(hidden, d)
370
+ nn.init.zeros_(out.weight)
371
+ nn.init.zeros_(out.bias)
372
+ self.net = nn.Sequential(nn.Linear(d, hidden), SquaredReLU(), out)
373
+ self.gate = nn.Parameter(torch.tensor(-3.0))
374
+
375
+ def forward(self, x):
376
+ return x + self.gate.sigmoid() * self.net(x)
377
+
378
+
379
+ class _BlockWithAdapter(nn.Module):
380
+ def __init__(self, block, adapter):
381
+ super().__init__()
382
+ self.block, self.adapter = block, adapter
383
+
384
+ def forward(self, *a, **k):
385
+ out = self.block(*a, **k)
386
+ if isinstance(out, tuple):
387
+ return (self.adapter(out[0]),) + out[1:]
388
+ return self.adapter(out)
389
+
390
+
391
+ def track_c(arms=("frozen", "aleph", "mlp"), steps=1500, batch=8, block=256,
392
+ seed=0, device="cuda", data_root=DATA_ROOT,
393
+ eval_every=500, save=True):
394
+ """GPT-2 124M frozen; adapters after every block; train adapters only."""
395
+ from transformers import GPT2LMHeadModel, GPT2TokenizerFast
396
+ if not torch.cuda.is_available():
397
+ raise RuntimeError("verdict runs are GPU-only")
398
+ tok = GPT2TokenizerFast.from_pretrained("gpt2")
399
+ tr_lines, va_lines = _wikitext_lines(data_root)
400
+ def to_stream(lines):
401
+ ids = tok("\n\n".join(lines), return_tensors="pt").input_ids[0]
402
+ return ids
403
+ stream_tr = to_stream(tr_lines[:8000])
404
+ stream_va = to_stream(va_lines[:1000])
405
+ ck_dir = os.path.join(data_root, "exp013", "ckpts")
406
+ os.makedirs(ck_dir, exist_ok=True)
407
+ results = {}
408
+ for arm in arms:
409
+ torch.manual_seed(seed)
410
+ g = torch.Generator().manual_seed(seed)
411
+ model = GPT2LMHeadModel.from_pretrained("gpt2").to(device)
412
+ for p in model.parameters():
413
+ p.requires_grad_(False)
414
+ adapters = []
415
+ if arm != "frozen":
416
+ d = model.config.n_embd
417
+ for i, blk in enumerate(model.transformer.h):
418
+ ad = (MslRelay(d) if arm == "aleph" else MLPAdapter(d)).to(device)
419
+ model.transformer.h[i] = _BlockWithAdapter(blk, ad)
420
+ adapters.append(ad)
421
+ params = [p for ad in adapters for p in ad.parameters()]
422
+ n_par = sum(p.numel() for p in params)
423
+ opt = torch.optim.Adam(params, lr=1e-3, weight_decay=0.0)
424
+ else:
425
+ params, n_par = [], 0
426
+ def eval_ppl():
427
+ model.eval()
428
+ with torch.no_grad():
429
+ ls = []
430
+ for j in range(0, stream_va.numel() - block - 1, block * 4):
431
+ x = stream_va[j:j + block].unsqueeze(0).to(device)
432
+ out = model(x, labels=x)
433
+ ls.append(out.loss.item())
434
+ model.train()
435
+ return math.exp(sum(ls) / len(ls))
436
+ if arm == "frozen":
437
+ ppl = eval_ppl()
438
+ print(f"[C frozen] ppl={ppl:.3f}", flush=True)
439
+ results["frozen"] = {"ppl": ppl}
440
+ continue
441
+ for step in range(1, steps + 1):
442
+ ix = torch.randint(0, stream_tr.numel() - block - 1, (batch,), generator=g)
443
+ x = torch.stack([stream_tr[i:i + block] for i in ix]).to(device)
444
+ loss = model(x, labels=x).loss
445
+ opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
446
+ if step % eval_every == 0 or step == steps:
447
+ ppl = eval_ppl()
448
+ gates = [round(ad.gate.sigmoid().item(), 4) for ad in adapters]
449
+ vit = {}
450
+ if arm == "aleph":
451
+ drifts = [round(anchor_drift(ad.addr.codebook, ad.addr.home)
452
+ ["mean"], 3) for ad in adapters]
453
+ vit = {"drift_by_depth": drifts}
454
+ print(f"[C {arm} s{seed}] step {step} ppl={ppl:.3f} "
455
+ f"params={n_par:,} gates={gates} {vit}", flush=True)
456
+ results[f"{arm}/s{seed}"] = {"ppl": ppl, "params": n_par, "gates": gates,
457
+ **vit}
458
+ if save and arm == "aleph":
459
+ torch.save({"track": "C", "arm": arm, "seed": seed, "ppl": ppl,
460
+ "state_dict": {f"relay{i}.{k}": v.cpu()
461
+ for i, ad in enumerate(adapters)
462
+ for k, v in ad.state_dict().items()}},
463
+ os.path.join(ck_dir, f"C_{arm}_s{seed}.pt"))
464
+ print(results, flush=True)
465
+ return results
466
+
467
+
468
+ # ================================================================ smoke ===========
469
+ def smoke():
470
+ """Shapes/parse only — no substrates, no training."""
471
+ for arm in ("linear", "mlp", "aleph", "sign"):
472
+ h = HeadArm(arm, 768)
473
+ y = h(torch.randn(2, 10, 768))
474
+ assert y.shape == (2, 10, 256)
475
+ y.sum().backward()
476
+ print(arm, "OK", f"{h.param_count():,}", h.vitals(torch.randn(2, 4, 768)))
477
+ dec = CharDecoder()
478
+ t = torch.tensor([dec.encode_word("hello") + [0] * 3,
479
+ dec.encode_word("worlds") + [0] * 2])
480
+ lg = dec(torch.randn(2, 256), t)
481
+ assert lg.shape[:2] == (2, t.shape[1] - 1)
482
+ print("decoder OK; greedy:", dec.greedy(torch.randn(2, 256)).shape)
483
+ ad = MLPAdapter(768)
484
+ assert ad(torch.randn(2, 4, 768)).shape == (2, 4, 768)
485
+ print("adapter OK — exp013 smoke passed (caches+tracks need GPU+transformers)")
486
+
487
+
488
+ def _in_notebook():
489
+ try:
490
+ get_ipython() # type: ignore[name-defined] # noqa: F821
491
+ return True
492
+ except NameError:
493
+ return False
494
+
495
+
496
+ if __name__ == "__main__":
497
+ if _in_notebook():
498
+ smoke()
499
+ print("Notebook: cache_clip()/cache_word_embeddings() then "
500
+ "track_b1() gate -> track_a() -> track_c().")
501
+ else:
502
+ import argparse
503
+ ap = argparse.ArgumentParser()
504
+ ap.add_argument("--track", default="smoke")
505
+ a, _ = ap.parse_known_args()
506
+ {"smoke": smoke, "a": track_a, "b1": track_b1, "c": track_c}[a.track]()
exp002_refine/geolip_vitals.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """geolip_vitals.py — shared diagnostic harness for the GeoLIP aleph experiments.
2
+ ALL functions are READOUTS: no gradients, no losses. CV is a readout, never a
3
+ force. Addressing is judged by drift->0.29154 and CV->0.20, never by recon cosine
4
+ (judgment criteria per the aleph-void article: https://huggingface.co/blog/AbstractPhil/geometric-vocabulary-patchwork-aleph-void).
5
+
6
+ Vitals provided:
7
+ anchor_drift — geodesic drift of anchors from init; binding fraction @0.29154
8
+ pentachoron_cv — CM 4-volume CV over random 5-row subsets (geovocab2 import)
9
+ axis_aliveness — oriented-address usage: axes alive, hppl, collapse flag
10
+ gate_stats — gate means vs the 0.012-0.03 band
11
+ path_diversity — unique-path counting, FIXED high-bits hash (low-16 bug is the
12
+ retracted artifact — never use the low bits)
13
+ grad_norm_spread — gradient democracy monitor (orders-of-magnitude spread)
14
+ CVScreen — CV@1000-batch early band screen (<0.30 LOW / .35-.50 MID / >.80 HIGH)
15
+
16
+ Smoke on a torch-capable env: python geolip_vitals.py
17
+ """
18
+ from __future__ import annotations
19
+ import math
20
+ import torch
21
+
22
+ BINDING = 0.29154 # radians; the binding/separation constant
23
+ CV_BAND = (0.13, 0.30) # CM CV band (discovery_catalog #4)
24
+ GATE_BAND = (0.012, 0.03) # live invariant candidate (acd_campaign)
25
+ KNUTH32 = 2654435761
26
+
27
+
28
+ # ----------------------------------------------------------------------------- drift
29
+ @torch.no_grad()
30
+ def anchor_drift(current: torch.Tensor, init: torch.Tensor, tol: float = 0.05) -> dict:
31
+ """Geodesic drift (radians) of each row of `current` from its row in `init`,
32
+ both row-normalized. Returns mean/std/per-row drift and the fraction of rows
33
+ within +/-tol of BINDING (the GLFM '46%' readout)."""
34
+ a = torch.nn.functional.normalize(current.float(), dim=-1)
35
+ b = torch.nn.functional.normalize(init.float(), dim=-1)
36
+ cos = (a * b).sum(-1).clamp(-1.0, 1.0)
37
+ drift = torch.arccos(cos)
38
+ frac = ((drift - BINDING).abs() <= tol).float().mean()
39
+ return {"mean": drift.mean().item(), "std": drift.std().item(),
40
+ "per_row": drift, "binding_fraction": frac.item()}
41
+
42
+
43
+ # -------------------------------------------------------------------------------- cv
44
+ @torch.no_grad()
45
+ def _pentachoron_volumes(pts: torch.Tensor) -> torch.Tensor:
46
+ """Batched Cayley-Menger 4-simplex volumes. pts: (B, 5, D) -> (B,) volumes.
47
+ One float64 det over all samples (vol^2 = -det(CM)/9216 for n=4). Built-in
48
+ for speed (the per-sample reference path is ~260x slower in a vitals loop);
49
+ geovocab2 remains the formula's reference implementation, parity-checked
50
+ via cv_reference_check()."""
51
+ B = pts.shape[0]
52
+ d2 = torch.cdist(pts.double(), pts.double()).pow(2) # (B,5,5)
53
+ cm = torch.ones(B, 6, 6, dtype=torch.float64, device=pts.device)
54
+ cm[:, 0, 0] = 0.0
55
+ cm[:, 1:, 1:] = d2
56
+ det = torch.linalg.det(cm)
57
+ return (-det / 9216.0).clamp_min(0.0).sqrt().float()
58
+
59
+
60
+ @torch.no_grad()
61
+ def pentachoron_cv(rows: torch.Tensor, n_samples: int = 200,
62
+ generator: torch.Generator | None = None) -> float:
63
+ """CV (std/mean) of Cayley-Menger 4-simplex volumes over n_samples random
64
+ 5-row subsets. Rows are row-normalized before measurement. Uses the built-in
65
+ batched CM (float64 det); validate against geovocab2 with
66
+ cv_reference_check() after any change to the volume math."""
67
+ x = torch.nn.functional.normalize(rows.float(), dim=-1)
68
+ n = x.shape[0]
69
+ if n < 5:
70
+ raise ValueError(f"pentachoron_cv needs >=5 rows, got {n}")
71
+ g = generator or torch.Generator(device="cpu").manual_seed(0)
72
+ idx = torch.stack([torch.randperm(n, generator=g)[:5]
73
+ for _ in range(n_samples)]) # (B,5)
74
+ v = _pentachoron_volumes(x[idx].cpu())
75
+ return (v.std() / v.mean().clamp_min(1e-12)).item()
76
+
77
+
78
+ @torch.no_grad()
79
+ def cv_reference_check(n_trials: int = 50, tol: float = 1e-5) -> float:
80
+ """Parity check of the built-in batched CM against geovocab2's reference
81
+ implementation (the formula's source of truth). Returns max |rel diff|;
82
+ raises if geovocab2 is absent or parity fails. Run after touching
83
+ _pentachoron_volumes."""
84
+ try:
85
+ from geovocab2.shapes.formula.symbolic.cayley_menger import (
86
+ CayleyMengerFromSimplex)
87
+ except Exception as e: # pragma: no cover
88
+ raise ImportError(
89
+ "cv_reference_check requires geovocab2 (install via the geolip-svae "
90
+ "umbrella: pip install git+https://github.com/AbstractEyes/"
91
+ "geolip-svae).") from e
92
+ ref = CayleyMengerFromSimplex()
93
+ g = torch.Generator().manual_seed(0)
94
+ pts = torch.nn.functional.normalize(
95
+ torch.randn(n_trials, 5, 4, generator=g), dim=-1)
96
+ mine = _pentachoron_volumes(pts)
97
+ # compare at float64: the reference computes in the INPUT dtype, and fp32
98
+ # dets lose up to ~4% on near-degenerate pentachora (measured 2026-07-11)
99
+ theirs = torch.stack([ref.forward(p.double())["volume"].float() for p in pts])
100
+ rel = ((mine - theirs).abs() / theirs.abs().clamp_min(1e-12)).max().item()
101
+ if rel > tol:
102
+ raise AssertionError(f"CM parity vs geovocab2 failed: max rel {rel}")
103
+ return rel
104
+
105
+
106
+ # ------------------------------------------------------------------------- aliveness
107
+ @torch.no_grad()
108
+ def axis_aliveness(oriented_weights: torch.Tensor, alive_thresh: float = 1e-3) -> dict:
109
+ """`oriented_weights`: (..., 2K) nonnegative oriented-softmax address rows
110
+ (sum to 1 on the last dim). Returns axes-alive count, mean-usage perplexity
111
+ (hppl analogue; healthy hosted reference 125-126/128), and a collapse flag.
112
+ Reference behavior: near-uniform aliveness at div_weight=0 (discovery #22)."""
113
+ w = oriented_weights.reshape(-1, oriented_weights.shape[-1]).float()
114
+ usage = w.mean(0)
115
+ usage = usage / usage.sum().clamp_min(1e-12)
116
+ # an axis is alive if its mean usage exceeds alive_thresh x the uniform share
117
+ alive = int((usage > alive_thresh * (1.0 / usage.numel())).sum())
118
+ ent = -(usage.clamp_min(1e-12) * usage.clamp_min(1e-12).log()).sum()
119
+ ppl = float(ent.exp())
120
+ return {"axes_total": usage.numel(), "axes_alive": alive, "usage_ppl": ppl,
121
+ "collapsed": ppl < 0.05 * usage.numel()}
122
+
123
+
124
+ # ------------------------------------------------------------------------------ gates
125
+ @torch.no_grad()
126
+ def gate_stats(gates: torch.Tensor) -> dict:
127
+ """Gate values (post-sigmoid/clamp). Reports mean and whether it sits in the
128
+ 0.012-0.03 band (read-only — the band is a candidate invariant, never a target)."""
129
+ g = gates.float().flatten()
130
+ m = g.mean().item()
131
+ return {"mean": m, "std": g.std().item(),
132
+ "in_band": GATE_BAND[0] <= m <= GATE_BAND[1]}
133
+
134
+
135
+ # ------------------------------------------------------------------------------ paths
136
+ @torch.no_grad()
137
+ def path_diversity(ids: torch.Tensor) -> dict:
138
+ """Unique-path counting with the FIXED multiplicative hash:
139
+ ((ids * 2654435761) % 2^32) >> 16 — Knuth needs the HIGH bits; the low-16
140
+ variant produced a retracted ~1,500 path ceiling in a prior campaign.
141
+ `ids`: integer tensor, one composed path id per row (any shape)."""
142
+ x = ids.reshape(-1).to(torch.int64)
143
+ hashed = ((x * KNUTH32) % (1 << 32)) >> 16
144
+ return {"n": int(x.numel()),
145
+ "unique_raw": int(torch.unique(x).numel()),
146
+ "unique_hashed": int(torch.unique(hashed).numel())}
147
+
148
+
149
+ @torch.no_grad()
150
+ def compose_path_ids(stage_indices: list[torch.Tensor], radix: int) -> torch.Tensor:
151
+ """Compose per-stage discrete indices (each (...,) int in [0, radix)) into a
152
+ single path id, positional base-`radix` — construction, not hashing."""
153
+ out = torch.zeros_like(stage_indices[0], dtype=torch.int64)
154
+ for s in stage_indices:
155
+ out = out * radix + s.to(torch.int64)
156
+ return out
157
+
158
+
159
+ # --------------------------------------------------------------------- grad democracy
160
+ @torch.no_grad()
161
+ def grad_norm_spread(groups: dict[str, list[torch.nn.Parameter]]) -> dict:
162
+ """Gradient-democracy monitor. `groups`: name -> params of one parallel member
163
+ (tower/expert). Reports per-group grad norms and the orders-of-magnitude spread.
164
+ Reference: unequalized heterogeneous towers spread ~20 orders (fibonacci dead at
165
+ 2.25e-21 under helix); equalized ~0.0 (geofractal gradient-democracy result)."""
166
+ norms = {}
167
+ for name, params in groups.items():
168
+ gs = [p.grad for p in params if p.grad is not None]
169
+ norms[name] = float(torch.sqrt(sum((g.float() ** 2).sum() for g in gs)).item()) \
170
+ if gs else 0.0
171
+ vals = [v for v in norms.values() if v > 0]
172
+ spread = (math.log10(max(vals)) - math.log10(min(vals))) if len(vals) >= 2 else 0.0
173
+ return {"norms": norms, "spread_orders": spread, "dead": [k for k, v in norms.items() if v == 0.0]}
174
+
175
+
176
+ # ----------------------------------------------------------------------------- screen
177
+ class CVScreen:
178
+ """CV@N early band screen (tri-band ft1): record pentachoron CV at `step_mark`
179
+ batches; classify <0.30 LOW / 0.35-0.50 MID / >0.80 HIGH. Turns ~2h/config
180
+ into ~7min. Readout only."""
181
+ def __init__(self, step_mark: int = 1000):
182
+ self.step_mark = step_mark
183
+ self.recorded: float | None = None
184
+
185
+ def maybe_record(self, step: int, rows: torch.Tensor) -> float | None:
186
+ if self.recorded is None and step >= self.step_mark:
187
+ self.recorded = pentachoron_cv(rows)
188
+ return self.recorded
189
+
190
+ @property
191
+ def band(self) -> str | None:
192
+ c = self.recorded
193
+ if c is None:
194
+ return None
195
+ if c < 0.30:
196
+ return "LOW"
197
+ if 0.35 <= c <= 0.50:
198
+ return "MID"
199
+ if c > 0.80:
200
+ return "HIGH"
201
+ return "BETWEEN"
202
+
203
+
204
+ # ------------------------------------------------------------------------------ smoke
205
+ if __name__ == "__main__": # shapes/parse smoke ONLY — no training, ever.
206
+ g = torch.Generator().manual_seed(0)
207
+ K, D = 64, 4
208
+ init = torch.nn.functional.normalize(torch.randn(K, D, generator=g), dim=-1)
209
+ cur = torch.nn.functional.normalize(init + 0.29 * torch.randn(K, D, generator=g), dim=-1)
210
+ print("drift:", {k: v for k, v in anchor_drift(cur, init).items() if k != "per_row"})
211
+ w = torch.softmax(torch.randn(32, 2 * K, generator=g), dim=-1)
212
+ print("aliveness:", axis_aliveness(w))
213
+ print("gates:", gate_stats(torch.full((8,), 0.024)))
214
+ ids = compose_path_ids([torch.randint(0, 16, (4096,), generator=g) for _ in range(4)], 16)
215
+ print("paths:", path_diversity(ids))
216
+ lin = torch.nn.Linear(8, 8)
217
+ lin(torch.randn(4, 8)).sum().backward()
218
+ print("democracy:", grad_norm_spread({"a": list(lin.parameters())}))
219
+ print("OK — vitals smoke passed (pentachoron_cv needs geovocab2; run on GPU env)")
exp002_refine/qwen_exp001_relay.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """qwen_exp001_relay.py — geolip-aleph-qwen EXPERIMENT 1: the relay retrofit
2
+ at 0.5B. The certified exp013 Track-C recipe (frozen trunk + near-zero-gated
3
+ multi-slot M_hat relays after every block, vs the param-matched zero-init MLP
4
+ adapter ablation) at its next scale rung: Qwen2.5-0.5B (24 blocks, d=896,
5
+ ~494M frozen params; relay stack ~2.8M trainable, <0.6%). First campaign of
6
+ the generation-stake line — judged on ppl, the GATE MECHANISM (do the gates
7
+ grow? exp013: aleph gates grew ~3x while MLP gates shrank), relay codebook
8
+ vitals, and GENERATED SAMPLES (the deliverable is a model that generates).
9
+
10
+ Arms (x2 seeds): frozen (eval-only baseline) | relay (MslRelay(896) after
11
+ every block) | mlp (param-matched MLPAdapter(896, hidden=64), zero-init out —
12
+ the exp013 ablation, 114,688 vs 114,944 params per adapter, 0.2%).
13
+ Corpus: wikitext-103-raw-v1 (HF parquet), ~12M-token cache; block 512,
14
+ batch 4, 3000 steps adapters-only, pure Adam lr 1e-3 wd 0 (the exp013
15
+ relay-training regime).
16
+ Riders: trunk FROZEN throughout; pure Adam wd=0; GPU-only verdicts; >=2
17
+ seeds; drift-check before any freeze claim; Colab-safe. Paste order:
18
+ geolip_vitals -> ar_differentiation_bed -> exp013_augmentation_bed -> this.
19
+ """
20
+ from __future__ import annotations
21
+ import json
22
+ import math
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+
28
+ if "MslRelay" not in globals():
29
+ try:
30
+ from ar_differentiation_bed import MslRelay
31
+ from exp013_augmentation_bed import MLPAdapter
32
+ from geolip_vitals import anchor_drift, axis_aliveness
33
+ except ImportError:
34
+ _here = globals().get("__file__")
35
+ if _here is None:
36
+ raise ImportError("paste geolip_vitals + ar_differentiation_bed + "
37
+ "exp013_augmentation_bed first")
38
+ import sys, pathlib
39
+ sys.path.insert(0, str(pathlib.Path(_here).parent))
40
+ from ar_differentiation_bed import MslRelay
41
+ from exp013_augmentation_bed import MLPAdapter
42
+ from geolip_vitals import anchor_drift, axis_aliveness
43
+
44
+ DATA_ROOT = os.environ.get("GEOLIP_DATA", "./data")
45
+ EXP_DIR = os.path.join(DATA_ROOT, "qwen_exp001")
46
+ BASE_MODEL = "Qwen/Qwen2.5-0.5B"
47
+ BLOCK, BATCH, STEPS, LR = 512, 4, 3000, 1e-3
48
+ MAX_TOKENS = 12_000_000
49
+ PROMPTS = ("The history of mathematics begins",
50
+ "In a small village by the sea,",
51
+ "The most important principle of engineering is")
52
+
53
+
54
+ class _QwenBlockWithAdapter(nn.Module):
55
+ """Wrap a Qwen2 decoder layer: adapter applied to the hidden-states output,
56
+ all other outputs and kwargs passed through untouched."""
57
+
58
+ def __init__(self, block, adapter):
59
+ super().__init__()
60
+ self.block, self.adapter = block, adapter
61
+
62
+ def forward(self, *args, **kwargs):
63
+ out = self.block(*args, **kwargs)
64
+ if isinstance(out, tuple):
65
+ return (self.adapter(out[0]),) + out[1:]
66
+ return self.adapter(out)
67
+
68
+
69
+ def _token_cache(device="cpu"):
70
+ """~12M-token wikitext-103 train stream + val stream, cached to disk."""
71
+ os.makedirs(EXP_DIR, exist_ok=True)
72
+ path = os.path.join(EXP_DIR, "tok_cache.pt")
73
+ if os.path.exists(path):
74
+ blob = torch.load(path, map_location="cpu", weights_only=True)
75
+ return blob["train"], blob["val"]
76
+ from huggingface_hub import hf_hub_download
77
+ import pyarrow.parquet as pq
78
+ from transformers import AutoTokenizer
79
+ tok = AutoTokenizer.from_pretrained(BASE_MODEL)
80
+
81
+ def stream(fname, cap):
82
+ p = hf_hub_download("Salesforce/wikitext", fname, repo_type="dataset")
83
+ lines = [t for t in pq.read_table(p).column("text").to_pylist()
84
+ if t and len(t.strip()) > 40]
85
+ ids = []
86
+ total = 0
87
+ chunk = []
88
+ csz = 0
89
+ for ln in lines:
90
+ chunk.append(ln)
91
+ csz += len(ln)
92
+ if csz > 500_000:
93
+ e = tok("".join(chunk), return_tensors="pt").input_ids[0]
94
+ ids.append(e)
95
+ total += e.numel()
96
+ chunk, csz = [], 0
97
+ if total >= cap:
98
+ break
99
+ if chunk and total < cap:
100
+ e = tok("".join(chunk), return_tensors="pt").input_ids[0]
101
+ ids.append(e)
102
+ return torch.cat(ids)[:cap]
103
+
104
+ tr = stream("wikitext-103-raw-v1/train-00000-of-00002.parquet", MAX_TOKENS)
105
+ va = stream("wikitext-103-raw-v1/validation-00000-of-00001.parquet",
106
+ 600_000)
107
+ torch.save({"train": tr, "val": va}, path)
108
+ print(f"token cache: train {tr.numel():,} val {va.numel():,}", flush=True)
109
+ return tr, va
110
+
111
+
112
+ def _batch(stream, batch, block, device, g):
113
+ ix = torch.randint(0, stream.numel() - block - 1, (batch,), generator=g)
114
+ x = torch.stack([stream[i:i + block] for i in ix]).to(device)
115
+ y = torch.stack([stream[i + 1:i + block + 1] for i in ix]).to(device)
116
+ return x.long(), y.long()
117
+
118
+
119
+ def load_qwen(arm: str, seed: int = 0, device="cuda"):
120
+ from transformers import AutoModelForCausalLM
121
+ torch.manual_seed(seed)
122
+ model = AutoModelForCausalLM.from_pretrained(BASE_MODEL,
123
+ torch_dtype=torch.float32)
124
+ model.config.use_cache = False
125
+ for p in model.parameters():
126
+ p.requires_grad_(False)
127
+ adapters = None
128
+ if arm != "frozen":
129
+ d = model.config.hidden_size
130
+ mk = (lambda: MslRelay(d)) if arm == "relay" else (lambda: MLPAdapter(d))
131
+ adapters = nn.ModuleList([mk() for _ in model.model.layers])
132
+ model.model.layers = nn.ModuleList(
133
+ [_QwenBlockWithAdapter(b, a)
134
+ for b, a in zip(model.model.layers, adapters)])
135
+ return model.to(device), adapters
136
+
137
+
138
+ @torch.no_grad()
139
+ def eval_ppl(model, va, device="cuda", n=40, g=None):
140
+ g = g or torch.Generator().manual_seed(0)
141
+ model.eval()
142
+ ls = []
143
+ for _ in range(n):
144
+ x, y = _batch(va, BATCH, BLOCK, device, g)
145
+ logits = model(input_ids=x).logits
146
+ ls.append(F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
147
+ y.reshape(-1)).item())
148
+ return math.exp(sum(ls) / len(ls))
149
+
150
+
151
+ @torch.no_grad()
152
+ def sample(model, device="cuda", max_new=80):
153
+ from transformers import AutoTokenizer
154
+ tok = AutoTokenizer.from_pretrained(BASE_MODEL)
155
+ model.eval()
156
+ model.config.use_cache = True
157
+ outs = {}
158
+ for p in PROMPTS:
159
+ ids = tok(p, return_tensors="pt").input_ids.to(device)
160
+ out = model.generate(ids, max_new_tokens=max_new, do_sample=False,
161
+ pad_token_id=tok.eos_token_id)
162
+ outs[p] = tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True)
163
+ model.config.use_cache = False
164
+ return outs
165
+
166
+
167
+ def adapter_vitals(adapters):
168
+ if adapters is None:
169
+ return None
170
+ gates = [round(torch.sigmoid(a.gate).item(), 4) for a in adapters
171
+ if hasattr(a, "gate")]
172
+ drifts = []
173
+ for a in adapters:
174
+ ad = getattr(a, "addr", None)
175
+ if ad is not None:
176
+ drifts.append(round(anchor_drift(ad.codebook, ad.home)["mean"], 3))
177
+ return {"gates": gates[:6] + ["..."] if len(gates) > 6 else gates,
178
+ "gate_mean": round(sum(gates) / max(len(gates), 1), 4),
179
+ "drift": drifts[:6] + ["..."] if len(drifts) > 6 else drifts}
180
+
181
+
182
+ def run_arm(arm: str, seed: int = 0, steps=STEPS, device="cuda"):
183
+ if not torch.cuda.is_available():
184
+ raise RuntimeError("verdict runs are GPU-only")
185
+ os.makedirs(EXP_DIR, exist_ok=True)
186
+ tr, va = _token_cache()
187
+ model, adapters = load_qwen(arm, seed=seed, device=device)
188
+ ledger = open(os.path.join(EXP_DIR, "ledger.jsonl"), "a", encoding="utf-8")
189
+ if arm == "frozen":
190
+ ppl = eval_ppl(model, va, device=device)
191
+ rec = {"exp": "q1", "arm": arm, "seed": seed, "ppl": round(ppl, 3),
192
+ "trainable": 0, "samples": sample(model, device=device)}
193
+ ledger.write(json.dumps(rec) + "\n"); ledger.flush()
194
+ print(f"[q1 frozen s{seed}] FINAL ppl={ppl:.3f}", flush=True)
195
+ ledger.close()
196
+ return ppl
197
+ g = torch.Generator().manual_seed(seed)
198
+ params = [p for p in adapters.parameters()]
199
+ n_train = sum(p.numel() for p in params)
200
+ opt = torch.optim.Adam(params, lr=LR, weight_decay=0.0)
201
+ model.train()
202
+ for step in range(1, steps + 1):
203
+ x, y = _batch(tr, BATCH, BLOCK, device, g)
204
+ logits = model(input_ids=x).logits
205
+ loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
206
+ y.reshape(-1))
207
+ opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
208
+ if step % 500 == 0:
209
+ v = adapter_vitals(adapters)
210
+ print(f"[q1 {arm} s{seed} step {step}] loss={loss.item():.3f} "
211
+ f"gate_mean={v['gate_mean']}", flush=True)
212
+ ppl = eval_ppl(model, va, device=device)
213
+ rec = {"exp": "q1", "arm": arm, "seed": seed, "ppl": round(ppl, 3),
214
+ "steps": steps, "trainable": n_train,
215
+ "vitals": adapter_vitals(adapters),
216
+ "samples": sample(model, device=device)}
217
+ ledger.write(json.dumps(rec) + "\n"); ledger.flush()
218
+ print(f"[q1 {arm} s{seed}] FINAL ppl={ppl:.3f} "
219
+ f"gate_mean={rec['vitals']['gate_mean']} trainable={n_train:,}",
220
+ flush=True)
221
+ torch.save({"arm": arm, "seed": seed,
222
+ "adapters": {k: v.cpu() for k, v in
223
+ adapters.state_dict().items()}},
224
+ os.path.join(EXP_DIR, f"q1_{arm}_s{seed}.pt"))
225
+ ledger.close()
226
+ del model, adapters
227
+ torch.cuda.empty_cache()
228
+ return ppl
229
+
230
+
231
+ def run_exp001(seeds=(0, 1), device="cuda"):
232
+ run_arm("frozen", seed=0, device=device) # baseline once (no training)
233
+ for seed in seeds:
234
+ for arm in ("relay", "mlp"):
235
+ run_arm(arm, seed=seed, device=device)
236
+ print("=== qwen exp001 COMPLETE ===", flush=True)
237
+
238
+
239
+ def smoke():
240
+ """Shapes/parse only — no substrate download, no training."""
241
+ r = MslRelay(896)
242
+ m = MLPAdapter(896)
243
+ x = torch.randn(2, 8, 896)
244
+ assert r(x).shape == x.shape and m(x).shape == x.shape
245
+ rp = sum(p.numel() for p in r.parameters())
246
+ mp = sum(p.numel() for p in m.parameters())
247
+ assert abs(rp - mp) / rp < 0.01, (rp, mp) # param-matched adapters
248
+ blk = nn.Linear(896, 896) # tuple-passthrough check
249
+ class TupBlock(nn.Module):
250
+ def forward(self, h, **kw):
251
+ return (blk(h), "aux")
252
+ w = _QwenBlockWithAdapter(TupBlock(), r)
253
+ out = w(x, position_ids=None)
254
+ assert isinstance(out, tuple) and out[0].shape == x.shape and out[1] == "aux"
255
+ (out[0].sum()).backward()
256
+ assert r.addr.codebook.grad is not None
257
+ print(f"qwen exp001 smoke passed (relay {rp:,} ~ mlp {mp:,} params/adapter;"
258
+ " full run needs GPU + transformers + the 0.5B download)")
259
+
260
+
261
+ def _in_notebook():
262
+ try:
263
+ get_ipython() # type: ignore[name-defined] # noqa: F821
264
+ return True
265
+ except NameError:
266
+ return False
267
+
268
+
269
+ if __name__ == "__main__":
270
+ smoke() if not _in_notebook() else (smoke(),
271
+ print("Notebook: run_exp001() on GPU."))
exp002_refine/qwen_exp002_refine.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """qwen_exp002_refine.py — geolip-aleph-qwen EXPERIMENT 2: refine the relay.
2
+ exp001 verdict shape: the relay retrofit works at 0.5B (frozen 17.80 ->
3
+ ~14.09, gates grow 0.047 -> 0.081 = trunk opt-in) but the param-matched MLP
4
+ adapter is at parity-or-ahead on ppl — the certified GPT-2 ordering did not
5
+ transfer as-is. exp002 races PROTOTYPICAL ENHANCEMENTS of the relay, each
6
+ grounded in a certified law, at an equalized WIDER budget (~230K/adapter),
7
+ against the honest wide MLP control.
8
+
9
+ Arms (frozen Qwen2.5-0.5B trunk, adapters after every block unless noted):
10
+ relay32 — MslRelay with n_slots=32 (slot dose-response: exp012 L-AR3,
11
+ task monotone in slot width)
12
+ relay_3tau — multi-slot read at 3 temperatures (0.05/0.1/0.3), concatenated
13
+ (the certified rule-of-3 stroboscope, exp012 v2: -1.08 bpb)
14
+ relay_pw — slots -> M_hat -> PATCHWORK consumer Linear(64,178) ->
15
+ SquaredReLU -> LN -> Linear(178,896) (the constellation
16
+ consumption spec replaces the bare linear out)
17
+ relay_deep — exp001's TOTAL budget concentrated on the last 12 blocks
18
+ (n_slots=32 there, nothing on blocks 0-11): the depth-gradient
19
+ law (cultivation concentrates near the prediction gradient)
20
+ as an architecture decision; total params == exp001 relay
21
+ mlp_wide — MLPAdapter hidden=128 (the wide-budget capacity control)
22
+ All near-zero gated (init -3.0). Training identical to exp001: block 512,
23
+ batch 4, 3000 steps, pure Adam lr 1e-3 wd 0, adapters only. Judged: val ppl
24
+ vs exp001's relay (14.093/14.091) and mlp (13.927/...) + gate mechanism +
25
+ vitals + generated samples. Seed 0 sweep first; seed 1 for the top arms.
26
+ Riders: trunk frozen; >=2 seeds before any claim; GPU-only; Colab-safe.
27
+ Paste order: geolip_vitals -> ar_differentiation_bed ->
28
+ exp013_augmentation_bed -> qwen_exp001_relay -> this file.
29
+ """
30
+ from __future__ import annotations
31
+ import json
32
+ import math
33
+ import os
34
+ import torch
35
+ import torch.nn as nn
36
+ import torch.nn.functional as F
37
+
38
+ if "run_arm" not in globals():
39
+ try:
40
+ from ar_differentiation_bed import AlephAddress, MslRelay
41
+ from exp013_augmentation_bed import MLPAdapter
42
+ from geolip_vitals import anchor_drift
43
+ from qwen_exp001_relay import (_QwenBlockWithAdapter, _token_cache,
44
+ _batch, eval_ppl, sample, EXP_DIR as
45
+ Q1_DIR, BASE_MODEL, BLOCK, BATCH, LR)
46
+ except ImportError:
47
+ _here = globals().get("__file__")
48
+ if _here is None:
49
+ raise ImportError("paste the qwen stack first")
50
+ import sys, pathlib
51
+ sys.path.insert(0, str(pathlib.Path(_here).parent))
52
+ from ar_differentiation_bed import AlephAddress, MslRelay
53
+ from exp013_augmentation_bed import MLPAdapter
54
+ from geolip_vitals import anchor_drift
55
+ from qwen_exp001_relay import (_QwenBlockWithAdapter, _token_cache,
56
+ _batch, eval_ppl, sample, EXP_DIR as
57
+ Q1_DIR, BASE_MODEL, BLOCK, BATCH, LR)
58
+
59
+ EXP2_DIR = os.path.join(os.path.dirname(Q1_DIR), "qwen_exp002")
60
+ STEPS = 3000
61
+
62
+
63
+ class SquaredReLU(nn.Module):
64
+ def forward(self, x):
65
+ return F.relu(x) ** 2
66
+
67
+
68
+ class Relay3Tau(nn.Module):
69
+ """Multi-slot M_hat at 3 temperatures, concatenated (rule-of-3 strobe)."""
70
+ TAUS = (0.05, 0.1, 0.3)
71
+
72
+ def __init__(self, d: int, n_slots: int = 16, K: int = 64):
73
+ super().__init__()
74
+ self.n_slots = n_slots
75
+ self.proj = nn.Linear(d, n_slots * 4, bias=False)
76
+ self.out = nn.Linear(n_slots * 4 * len(self.TAUS), d, bias=False)
77
+ nn.init.orthogonal_(self.proj.weight)
78
+ nn.init.orthogonal_(self.out.weight)
79
+ self.addr = AlephAddress(K, 4)
80
+ self.gate = nn.Parameter(torch.tensor(-3.0))
81
+
82
+ def forward(self, x):
83
+ B, n, _ = x.shape
84
+ slots = self.proj(x).view(B, n, self.n_slots, 4)
85
+ feats = []
86
+ for t in self.TAUS:
87
+ u = self.addr._u(slots) * (self.addr.tau / t)
88
+ m = u.abs().amax(dim=-1, keepdim=True)
89
+ ep, en = torch.exp(u - m), torch.exp(-u - m)
90
+ A = F.normalize(self.addr.codebook, dim=-1)
91
+ feats.append((((ep - en) @ A)
92
+ / (ep + en).sum(dim=-1, keepdim=True)).reshape(B, n, -1))
93
+ return x + torch.sigmoid(self.gate) * self.out(torch.cat(feats, -1))
94
+
95
+
96
+ class RelayPatchwork(nn.Module):
97
+ """Multi-slot M_hat -> constellation-spec consumer (SquaredReLU patchwork)."""
98
+
99
+ def __init__(self, d: int, n_slots: int = 16, K: int = 64, hidden: int = 178):
100
+ super().__init__()
101
+ self.n_slots = n_slots
102
+ self.proj = nn.Linear(d, n_slots * 4, bias=False)
103
+ nn.init.orthogonal_(self.proj.weight)
104
+ self.addr = AlephAddress(K, 4)
105
+ self.consume = nn.Sequential(
106
+ nn.Linear(n_slots * 4, hidden), SquaredReLU(),
107
+ nn.LayerNorm(hidden), nn.Linear(hidden, d))
108
+ nn.init.zeros_(self.consume[-1].weight) # zero-init out (theme D)
109
+ self.gate = nn.Parameter(torch.tensor(-3.0))
110
+
111
+ def forward(self, x):
112
+ B, n, _ = x.shape
113
+ slots = self.proj(x).view(B, n, self.n_slots, 4)
114
+ feats = self.addr.m_hat(slots).reshape(B, n, -1)
115
+ return x + torch.sigmoid(self.gate) * self.consume(feats)
116
+
117
+
118
+ def build_adapters(arm: str, model):
119
+ d = model.config.hidden_size
120
+ L = len(model.model.layers)
121
+ if arm == "relay32":
122
+ mk = [lambda: MslRelay(d, n_slots=32) for _ in range(L)]
123
+ elif arm == "relay_3tau":
124
+ mk = [lambda: Relay3Tau(d) for _ in range(L)]
125
+ elif arm == "relay_pw":
126
+ mk = [lambda: RelayPatchwork(d) for _ in range(L)]
127
+ elif arm == "relay_deep":
128
+ mk = [None] * (L // 2) + [lambda: MslRelay(d, n_slots=32)
129
+ for _ in range(L - L // 2)]
130
+ elif arm == "mlp_wide":
131
+ mk = [lambda: MLPAdapter(d, hidden=128) for _ in range(L)]
132
+ else:
133
+ raise ValueError(arm)
134
+ adapters = nn.ModuleList([m() if m else nn.Identity() for m in mk])
135
+ model.model.layers = nn.ModuleList(
136
+ [_QwenBlockWithAdapter(b, a) if not isinstance(a, nn.Identity) else b
137
+ for b, a in zip(model.model.layers, adapters)])
138
+ return adapters
139
+
140
+
141
+ def adapter_vitals(adapters):
142
+ gates, drifts = [], []
143
+ for a in adapters:
144
+ if hasattr(a, "gate"):
145
+ gates.append(round(torch.sigmoid(a.gate).item(), 4))
146
+ ad = getattr(a, "addr", None)
147
+ if ad is not None:
148
+ drifts.append(round(anchor_drift(ad.codebook, ad.home)["mean"], 3))
149
+ return {"gate_mean": round(sum(gates) / max(len(gates), 1), 4),
150
+ "gates_head_tail": gates[:3] + gates[-3:],
151
+ "drift_head_tail": (drifts[:3] + drifts[-3:]) if drifts else None}
152
+
153
+
154
+ def run_arm2(arm: str, seed: int = 0, steps=STEPS, device="cuda"):
155
+ if not torch.cuda.is_available():
156
+ raise RuntimeError("verdict runs are GPU-only")
157
+ os.makedirs(EXP2_DIR, exist_ok=True)
158
+ from transformers import AutoModelForCausalLM
159
+ tr, va = _token_cache()
160
+ torch.manual_seed(seed)
161
+ model = AutoModelForCausalLM.from_pretrained(BASE_MODEL,
162
+ torch_dtype=torch.float32)
163
+ model.config.use_cache = False
164
+ for p in model.parameters():
165
+ p.requires_grad_(False)
166
+ adapters = build_adapters(arm, model)
167
+ model = model.to(device)
168
+ n_train = sum(p.numel() for p in adapters.parameters())
169
+ g = torch.Generator().manual_seed(seed)
170
+ opt = torch.optim.Adam(adapters.parameters(), lr=LR, weight_decay=0.0)
171
+ model.train()
172
+ for step in range(1, steps + 1):
173
+ x, y = _batch(tr, BATCH, BLOCK, device, g)
174
+ logits = model(input_ids=x).logits
175
+ loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
176
+ y.reshape(-1))
177
+ opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
178
+ if step % 1000 == 0:
179
+ print(f"[q2 {arm} s{seed} step {step}] loss={loss.item():.3f}",
180
+ flush=True)
181
+ ppl = eval_ppl(model, va, device=device)
182
+ v = adapter_vitals(adapters)
183
+ rec = {"exp": "q2", "arm": arm, "seed": seed, "ppl": round(ppl, 3),
184
+ "steps": steps, "trainable": n_train, "vitals": v,
185
+ "samples": sample(model, device=device)}
186
+ ledger = open(os.path.join(EXP2_DIR, "ledger.jsonl"), "a", encoding="utf-8")
187
+ ledger.write(json.dumps(rec) + "\n"); ledger.close()
188
+ print(f"[q2 {arm} s{seed}] FINAL ppl={ppl:.3f} gate_mean={v['gate_mean']} "
189
+ f"trainable={n_train:,}", flush=True)
190
+ torch.save({"arm": arm, "seed": seed,
191
+ "adapters": {k: v2.cpu() for k, v2 in
192
+ adapters.state_dict().items()}},
193
+ os.path.join(EXP2_DIR, f"q2_{arm}_s{seed}.pt"))
194
+ del model, adapters
195
+ torch.cuda.empty_cache()
196
+ return ppl
197
+
198
+
199
+ ARMS = ("relay32", "relay_3tau", "relay_pw", "relay_deep", "mlp_wide")
200
+
201
+
202
+ def run_wave_a(arms=ARMS, seed=0, device="cuda"):
203
+ for arm in arms:
204
+ run_arm2(arm, seed=seed, device=device)
205
+ print("=== qwen exp002 WAVE A COMPLETE ===", flush=True)
206
+
207
+
208
+ def smoke():
209
+ x = torch.randn(2, 8, 896)
210
+ for cls, kw in ((Relay3Tau, {}), (RelayPatchwork, {}),):
211
+ a = cls(896, **kw)
212
+ y = a(x)
213
+ assert y.shape == x.shape
214
+ y.sum().backward()
215
+ assert a.addr.codebook.grad is not None
216
+ a.zero_grad()
217
+ p32 = sum(p.numel() for p in MslRelay(896, n_slots=32).parameters())
218
+ p3t = sum(p.numel() for p in Relay3Tau(896).parameters())
219
+ ppw = sum(p.numel() for p in RelayPatchwork(896).parameters())
220
+ pmw = sum(p.numel() for p in MLPAdapter(896, hidden=128).parameters())
221
+ lo, hi = min(p32, p3t, ppw, pmw), max(p32, p3t, ppw, pmw)
222
+ assert (hi - lo) / hi < 0.12, (p32, p3t, ppw, pmw) # budget-equalized ~10%
223
+ print(f"qwen exp002 smoke passed (relay32 {p32:,} | 3tau {p3t:,} | "
224
+ f"pw {ppw:,} | mlp_wide {pmw:,} per adapter)")
225
+
226
+
227
+ def _in_notebook():
228
+ try:
229
+ get_ipython() # type: ignore[name-defined] # noqa: F821
230
+ return True
231
+ except NameError:
232
+ return False
233
+
234
+
235
+ if __name__ == "__main__":
236
+ smoke() if not _in_notebook() else (smoke(),
237
+ print("Notebook: run_wave_a() on GPU."))
exp002_refine/repro.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """repro.py — standalone loader/runner for exp002_refine. Code dependencies
2
+ live in THIS folder (geolip_vitals.py, ar_differentiation_bed.py,
3
+ exp013_augmentation_bed.py, qwen_exp001_relay.py, qwen_exp002_refine.py).
4
+
5
+ python repro.py # CPU smoke: all variants + budget match
6
+ python repro.py --run # Wave A (5 arms, seed 0; GPU ~3h)
7
+ python repro.py --arm relay_pw --seed 1 --steps 6000 # any single cell
8
+
9
+ Data + token cache land in ./data (override with GEOLIP_DATA).
10
+ """
11
+ import os
12
+ import sys
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ sys.path.insert(0, HERE)
16
+
17
+ if __name__ == "__main__":
18
+ import geolip_vitals # noqa: F401 (paste order)
19
+ import ar_differentiation_bed # noqa: F401
20
+ import exp013_augmentation_bed # noqa: F401
21
+ import qwen_exp001_relay # noqa: F401
22
+ import qwen_exp002_refine as q2
23
+ args = sys.argv[1:]
24
+ if "--run" in args:
25
+ q2.run_wave_a()
26
+ elif "--arm" in args:
27
+ import argparse
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--arm", required=True, choices=q2.ARMS)
30
+ ap.add_argument("--seed", type=int, default=0)
31
+ ap.add_argument("--steps", type=int, default=3000)
32
+ a, _ = ap.parse_known_args()
33
+ q2.run_arm2(a.arm, seed=a.seed, steps=a.steps)
34
+ else:
35
+ q2.smoke()
36
+ print("repro smoke passed — --run (wave A) or --arm <name> (one cell)")
exp002_refine/results/companion_mlp6k.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"exp": "q1", "arm": "mlp", "seed": 0, "ppl": 13.899, "steps": 6000, "trainable": 2775576, "vitals": {"gates": [0.0399, 0.0381, 0.0375, 0.0375, 0.0358, 0.0333, "..."], "gate_mean": 0.0292, "drift": []}, "samples": {"The history of mathematics begins": " with the ancient civilizations of Mesopotamia , Egypt , and Greece . The Babylonians , who lived in the 2nd millennium BC , were the first to develop a system of mathematics that included the use of fractions . The Egyptians , who lived in the 2nd millennium BC , developed a system of mathematics that included the use of fractions and the use of the decimal system . The Greeks ,", "In a small village by the sea,": " a young man named John is a member of the local gang . He is a member of the gang known as the \" Black Gang \" , and is a member of the gang known as the \" White Gang \" . John is a member of the gang known as the \" Black Gang \" , and is a member of the gang known as the \" White Gang \" . John is a member of the gang", "The most important principle of engineering is": " to ensure that the design is safe and reliable . The design of a building is a complex process that involves many factors , including the materials used , the construction methods , and the design of the building itself . The design of a building is also influenced by the building owner 's needs and preferences . \n The design of a building is a complex process that involves many factors , including the materials used , the"}}
exp002_refine/results/ledger.jsonl ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {"exp": "q2", "arm": "relay32", "seed": 0, "ppl": 14.089, "steps": 3000, "trainable": 5511192, "vitals": {"gate_mean": 0.0606, "gates_head_tail": [0.0548, 0.0488, 0.0495, 0.134, 0.1166, 0.0854], "drift_head_tail": [0.133, 0.115, 0.144, 0.243, 0.33, 0.205]}, "samples": {"The history of mathematics begins": " with the ancient Babylonians , who developed a system of mathematics that was based on the concept of zero . The Babylonians used a base @-@ ten numeral system , and their arithmetic was based on multiplication and division . The Babylonians also developed a system of astronomy , which included the concept of zero . \n The ancient Egyptians developed a system of mathematics based on the concept of zero , and used it", "In a small village by the sea,": " a young man named Tom is a good friend of the village 's old man , Mr. Brown . Tom is a good boy , but he is not very good at his lessons . Mr. Brown is a good teacher , but he is not very good at teaching . Tom is often late for school , and Mr. Brown is often late for work . Tom is often late for school , and Mr", "The most important principle of engineering is": " to make the best use of the materials and energy available . This principle is expressed in the following equation : \n The equation is a mathematical expression of the law of conservation of energy . \n The equation is a mathematical expression of the law of conservation of energy . \n The equation is a mathematical expression of the law of conservation of energy . \n The equation is a mathematical expression of the law of conservation of energy"}}
2
+ {"exp": "q2", "arm": "relay_3tau", "seed": 0, "ppl": 14.112, "steps": 3000, "trainable": 5511192, "vitals": {"gate_mean": 0.0445, "gates_head_tail": [0.0385, 0.034, 0.0336, 0.0981, 0.0983, 0.07], "drift_head_tail": [0.125, 0.134, 0.109, 0.193, 0.26, 0.139]}, "samples": {"The history of mathematics begins": " with the ancient Babylonians , who developed a system of mathematics that was based on the concept of zero . The Babylonians used a base @-@ ten system , and their numbers were written in a base @-@ ten positional notation . The Babylonians also developed a system of arithmetic , which was based on the concept of place value . The Babylonians also developed a system of geometry , which was", "In a small village by the sea,": " a young man named Tom is a good swimmer . He is also a good swimmer at the beach . He is a good swimmer at the beach , but he is not good at swimming in the sea . He is a good swimmer at the sea , but he is not good at swimming in the beach . \n Tom is a good swimmer at the beach , but he is not good", "The most important principle of engineering is": " to make the best use of the materials and energy available . This principle is expressed in the following way : \n \" The best use of materials and energy is to make the most efficient use of them . \" \n The term \" efficiency \" is used to describe the ratio of the useful work output to the total energy input . The efficiency of a machine is the ratio of the output power to the input power"}}
3
+ {"exp": "q2", "arm": "relay_pw", "seed": 0, "ppl": 13.982, "steps": 3000, "trainable": 5517864, "vitals": {"gate_mean": 0.0366, "gates_head_tail": [0.0407, 0.0258, 0.0259, 0.0731, 0.0627, 0.0555], "drift_head_tail": [0.13, 0.1, 0.088, 0.107, 0.105, 0.115]}, "samples": {"The history of mathematics begins": " with the ancient Babylonians , who developed a system of mathematics that was based on the use of sexagesimal ( base 60 ) numbers . The Babylonians used a sexagesimal system to measure time , and to solve problems in geometry . The Babylonians also developed a system of algebra , which was based on the use of sexagesimal numbers . The Babylonians used sexagesimal numbers", "In a small village by the sea,": " a young man named John is a skilled sailor . He is a good friend of a young woman named Sarah , who is also a sailor . John and Sarah are married and have a son named Jack . \n John and Sarah are married and have a son named Jack . John and Sarah are married and have a son named Jack . John and Sarah are married and have a son named Jack . John and Sarah", "The most important principle of engineering is": " to make the best use of the materials and energy available . This principle is expressed in the following equation : \n The equation is a mathematical expression of the principle of conservation of energy . The energy in the system is the sum of the energy of the system and the energy of the surroundings . The energy of the system is the sum of the energy of the system and the energy of the surroundings . The energy"}}
4
+ {"exp": "q2", "arm": "relay_deep", "seed": 0, "ppl": 14.576, "steps": 3000, "trainable": 2755596, "vitals": {"gate_mean": 0.0942, "gates_head_tail": [0.0992, 0.0765, 0.0703, 0.1419, 0.1192, 0.0884], "drift_head_tail": [0.209, 0.191, 0.188, 0.252, 0.321, 0.186]}, "samples": {"The history of mathematics begins": " with the ancient Babylonians , who developed a system of mathematics that was based on the decimal system . The Babylonians used a base @-@ ten system , and their calculations were based on the sexagesimal system , which is the system of measuring angles in degrees , minutes , and seconds . The Babylonians also developed a system of algebra , which was based on the concept of a variable , and", "In a small village by the sea,": " there are two small islands , the small island is 100 meters ( 328 feet ) long and 50 meters ( 164 feet ) wide , and the large island is 150 meters ( 490 feet ) long and 75 meters ( 248 feet ) wide . The small island is 10 meters ( 3", "The most important principle of engineering is": " to ensure the safety of the people . This is because the safety of the people is the foundation of the safety of the country . \n The safety of the people is the foundation of the safety of the country . \n The safety of the people is the foundation of the safety of the country . \n The safety of the people is the foundation of the safety of the country . \n The safety of the people"}}
5
+ {"exp": "q2", "arm": "mlp_wide", "seed": 0, "ppl": NaN, "steps": 3000, "trainable": 5529624, "vitals": {"gate_mean": NaN, "gates_head_tail": [NaN, NaN, NaN, NaN, NaN, NaN], "drift_head_tail": null}, "samples": {"The history of mathematics begins": "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "In a small village by the sea,": "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "The most important principle of engineering is": "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"}}
6
+ {"exp": "q2", "arm": "relay_pw", "seed": 1, "ppl": 14.012, "steps": 3000, "trainable": 5517864, "vitals": {"gate_mean": 0.0372, "gates_head_tail": [0.0386, 0.0269, 0.0254, 0.0712, 0.062, 0.0534], "drift_head_tail": [0.081, 0.087, 0.101, 0.106, 0.128, 0.104]}, "samples": {"The history of mathematics begins": " with the ancient Babylonians , who developed a system of mathematics that was based on the use of sexagesimal ( base @-@ 60 ) numbers . The Babylonians used a sexagesimal system to represent numbers , and they used a base @-@ 60 positional numeral system . The Babylonians used a sexagesimal system to represent numbers , and they used a base @", "In a small village by the sea,": " there are 100 houses . Each house has a dog , and each dog has a collar . The number of dogs in the village is 10 more than the number of houses . How many dogs are there in the village ? \n To determine the number of dogs in the village , we start by defining the variables and setting up the equation based on the given information . Let \\( d \\", "The most important principle of engineering is": " to make the best use of the materials available . This is a very broad principle , and it is not always easy to apply it to a particular problem . The most important principle of engineering is to make the best use of the materials available . This is a very broad principle , and it is not always easy to apply it to a particular problem . The most important principle of engineering is to make the best"}}
7
+ {"exp": "q2", "arm": "mlp_wide", "seed": 1, "ppl": 13.93, "steps": 3000, "trainable": 5529624, "vitals": {"gate_mean": 0.0366, "gates_head_tail": [0.0441, 0.0409, 0.0398, 0.0261, 0.0286, 0.0246], "drift_head_tail": null}, "samples": {"The history of mathematics begins": " with the ancient civilizations of Mesopotamia , Egypt , and Greece . The Babylonians , who lived in the 19th century BC , were the first to use a base @-@ 10 positional numeral system , and they were the first to use zero as a place holder . The Egyptians used a base @-@ 20 positional numeral system , and the Greeks used a", "In a small village by the sea,": " a young man named John is a skilled sailor and a skilled fisherman . He is also a skilled hunter and a skilled tracker . He is also a skilled thief . He is also a skilled thief . He is also a skilled thief . He is also a skilled thief . He is also a skilled thief . He is also a skilled thief . He is also a skilled thief . He is also a skilled", "The most important principle of engineering is": " that of safety . The engineer is responsible for the safety of the people who use his services . The engineer is responsible for the safety of the people who use his services . The engineer is responsible for the safety of the people who use his services . The engineer is responsible for the safety of the people who use his services . The engineer is responsible for the safety of the people who use his services . The"}}
8
+ {"exp": "q2", "arm": "relay32", "seed": 1, "ppl": 14.069, "steps": 3000, "trainable": 5511192, "vitals": {"gate_mean": 0.0613, "gates_head_tail": [0.0535, 0.0497, 0.0495, 0.1354, 0.1159, 0.0853], "drift_head_tail": [0.156, 0.147, 0.133, 0.261, 0.358, 0.185]}, "samples": {"The history of mathematics begins": " with the ancient civilizations of Mesopotamia , Egypt , and Greece . The Babylonians , for example , developed a system of mathematics that was based on the concept of zero , which was used to represent the absence of a quantity . The Egyptians used a sexagesimal ( base 60 ) numeral system , which was based on the fact that 60 is the number of days in a", "In a small village by the sea,": " there are 100 houses . Each house has a dog , and each dog has a collar . The number of dogs in the village is 10 more than the number of dogs in the village with a collar . How many dogs are there in the village with a collar ? \n To solve this problem , we can set up a system of equations based on the information given . Let 's", "The most important principle of engineering is": " to make the best use of the materials and energy available . The most important principle of engineering is to make the best use of the materials and energy available . \n The most important principle of engineering is to make the best use of the materials and energy available . The most important principle of engineering is to make the best use of the materials and energy available . \n The most important principle of engineering is to make"}}
9
+ {"exp": "q2", "arm": "relay_pw", "seed": 0, "ppl": 13.983, "steps": 6000, "trainable": 5517864, "vitals": {"gate_mean": 0.0387, "gates_head_tail": [0.0368, 0.0225, 0.0239, 0.0836, 0.0704, 0.0632], "drift_head_tail": [0.167, 0.131, 0.118, 0.132, 0.146, 0.154]}, "samples": {"The history of mathematics begins": " with the ancient civilizations of Mesopotamia , Egypt , and China . The Babylonians developed a base 60 positional notation system , and the Chinese developed a base 10 positional notation system . The ancient Greeks developed a base 10 positional notation system , and the Babylonians developed a base 60 positional notation system . The Babylonians used a base 60 positional notation system", "In a small village by the sea,": " a young man named Tom is a skilled sailor . He is a good swimmer and a good swimmer at sea . He is also a good swimmer on land . He is a good swimmer in the sea and on land . He is a good swimmer in the sea and on land . He is a good swimmer in the sea and on land . He is a good swimmer in", "The most important principle of engineering is": " to make the best use of the materials available . The materials used in the construction of a building are not only the materials used in the construction of the building itself , but also the materials used in the construction of the building 's supporting structures . The materials used in the construction of the supporting structures are not only the materials used in the construction of the supporting structures themselves , but also the materials used in"}}
exp002_refine/results/results.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ppl": {
3
+ "relay32_s0_t3000": 14.089,
4
+ "relay_3tau_s0_t3000": 14.112,
5
+ "relay_pw_s0_t3000": 13.982,
6
+ "relay_deep_s0_t3000": 14.576,
7
+ "mlp_wide_s0_t3000": NaN,
8
+ "relay_pw_s1_t3000": 14.012,
9
+ "mlp_wide_s1_t3000": 13.93,
10
+ "relay32_s1_t3000": 14.069,
11
+ "relay_pw_s0_t6000": 13.983
12
+ },
13
+ "companion_mlp6k": 13.899,
14
+ "n_rows": 10
15
+ }