phera-ra commited on
Commit
44f49ac
·
verified ·
1 Parent(s): 220ff1c

State ladder: the section-3 mechanism works, and coupling is what makes it work

Browse files

The Hebbian kernel was reported null three times. All three were the instrument:
Omega summed over the wrong axis (Omega == 1.0, H all-ones, cancels in softmax);
a saturated sigmoid gate; a clamp with zero gradient at its bound; and underneath
all of it sigma hardcoded to 1 against a measured state spread of 61.98, which
made H the identity matrix. Section 3.2 never assigns sigma a value.

Corrected, and with the paper's phi-governed scaffold built for the first time
(RMSNorm, RoPE, d_ff = floor(d*phi), phi-scaled init), every configuration beats
its baseline on every seed:

none 1.44680
dyn12 1.39773 -0.049 t=-10.5 2,412 extra params
dyn54 1.39118 -0.056 t=-3.9 concatenated 12D+42D
static54 1.37218 -0.075 t=-7.4
dyn42 1.37521 -0.072 t=-7.9
tri 1.29152 -0.155 t=-40.8 12D and 42D COUPLED

Concatenating the two states is worse than a plain projection; coupling them is
the largest effect in the project, for 12,730 extra parameters. The coupling
matrices grow 3.0-3.4x during training and real-word rate stays above baseline,
so it is the coupling and not the capacity.

Also: dyn12 returns 66% of a projection 17x its size at 11x the parameter
efficiency. The paper's "smaller model beats larger" did not hold; "state is
cheaper than weights" did.

Adds section 4c on the preflight discipline that caught all four inert
mechanisms, and clarifies that section 4's quantum nulls are a separate question
from the architecture result.

FINDINGS.md CHANGED
@@ -128,10 +128,13 @@ drive.
128
  ## 6. Null results: the ones that matter most
129
 
130
  Quantum entropy was injected at **six** distinct points. **All six are null** against
131
- matched classical controls. A seventh test, of the §3 CST kernel, was recorded as null,
132
- **retracted**, and has now been re-run three times — because the first three harnesses
133
- each broke the mechanism in a different way. The final number is also null, and this time
134
- it was earned.
 
 
 
135
 
136
  | injection site | result |
137
  |---|---|
@@ -141,7 +144,8 @@ it was earned.
141
  | spatial 54D seed (full pipeline) | null. Real seed beat **0/8** random vectors, z = −1.75 |
142
  | entanglement matrix as attention kernel | null. **Worse** than plain attention, 3/3 seeds, t = −18.6 |
143
  | live sensory state as prompt text | null. n=40 paired, blind-judged, CI crosses zero |
144
- | §3 Hebbian kernel in a generative model | null **after three harness repairs**. CST worse by +0.0143 loss, 0/3 seeds, gate alive at 0.047. See below |
 
145
 
146
  ### Retraction: the §3 kernel result
147
 
@@ -231,7 +235,108 @@ Two honest caveats, pointing opposite ways:
231
 
232
  **What this does not settle.** This tests the §3 kernel inside a *conventional* transformer:
233
  LayerNorm, learned absolute positions, a 4:1 GELU feed-forward. The paper specifies none of
234
- those — see §11. A φ-governed replication is pending.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
  *The retraction above is kept rather than deleted because it is the clearest example in this
237
  document of the failure mode described in §8: a confident negative that was entirely about
@@ -409,9 +514,13 @@ weights whose every initial value came from measured IBM Quantum hardware. What
409
  it: the φ-governed scaffold the paper specifies — RMSNorm, RoPE, `d_ff = ⌊d·φ⌋`, φ-scaled
410
  initialisation. The shipped architecture implements §3's kernel inside a conventional
411
  transformer. A grep of the source tree found no implementation of the φ scaffold at all,
412
- which means every §3 measurement in §6 was made in the wrong building. That replication is
413
- pending, and until it lands the §6 result should be read as *"the kernel does not help in a
414
- conventional transformer"*, not as a verdict on the paper.
 
 
 
 
415
 
416
  ---
417
 
 
128
  ## 6. Null results: the ones that matter most
129
 
130
  Quantum entropy was injected at **six** distinct points. **All six are null** against
131
+ matched classical controls. That is the correct outcome and §6 explains why.
132
+
133
+ A seventh test — of the §3 CST kernel, which is an *architecture* claim rather than a
134
+ quantum one — was recorded as null, **retracted**, and re-run four times. The first three
135
+ harnesses each broke the mechanism in a different way. The fourth revealed that the test
136
+ had also been run in the wrong architecture. Corrected, **it is the one positive result in
137
+ this document**: 6/6 seeds, t = −6.56 and −14.34.
138
 
139
  | injection site | result |
140
  |---|---|
 
144
  | spatial 54D seed (full pipeline) | null. Real seed beat **0/8** random vectors, z = −1.75 |
145
  | entanglement matrix as attention kernel | null. **Worse** than plain attention, 3/3 seeds, t = −18.6 |
146
  | live sensory state as prompt text | null. n=40 paired, blind-judged, CI crosses zero |
147
+ | §3 Hebbian kernel, **conventional** transformer | null. CST worse by +0.0143, 0/3 seeds. See below |
148
+ | §3 Hebbian kernel, **φ-governed** transformer | **NOT NULL. CST better by −0.044 (t=−6.56) and −0.155 (t=−14.34), 6/6 seeds across two dimension variants.** The one positive result in this document |
149
 
150
  ### Retraction: the §3 kernel result
151
 
 
235
 
236
  **What this does not settle.** This tests the §3 kernel inside a *conventional* transformer:
237
  LayerNorm, learned absolute positions, a 4:1 GELU feed-forward. The paper specifies none of
238
+ those. That turned out to be the whole story.
239
+
240
+ ### The φ-governed replication: §3 works
241
+
242
+ The paper specifies RMSNorm (§2.3), RoPE (§2.4), `d_ff = ⌊d_model × φ⌋` (§2.2), φ-scaled
243
+ initialisation (§6.2) and a `PhiGatedFFN` (§2.1). A search of the source tree found **no
244
+ implementation of any of it**. Every measurement above was made in the wrong building.
245
+
246
+ Built faithfully and re-run at two dimension variants — A: d_model 192, 4 heads; B: d_model
247
+ 199 = φ¹¹, 1 head — same corpus, same quantum-born init, same seeds, gate free:
248
+
249
+ | scaffold | PLAIN | CST | delta | t | CST wins | mean gate |
250
+ |---|---|---|---|---|---|---|
251
+ | conventional | 1.40312 | 1.41739 | +0.0143 | +3.90 | 0/3 | 0.047 |
252
+ | **φ-governed A** | 1.23680 | **1.19255** | **−0.0443** | **−6.56** | **3/3** | 0.096 |
253
+ | **φ-governed B** | 1.42867 | **1.27352** | **−0.1552** | **−14.34** | **3/3** | 0.093 |
254
+
255
+ **6/6 seeds across both variants.** The gate rose from 0.018 to ~0.096 in every run — the
256
+ optimiser asking for five times more kernel than it started with — and σ kept adapting after
257
+ calibration (26.8 → 18.8 at layer 0). The mechanism was actively tuned, not merely tolerated.
258
+
259
+ **Credit where the measurement puts it.** The scaffold is the larger share:
260
+
261
+ ```
262
+ conventional PLAIN 1.40312
263
+ φ PLAIN 1.23680 scaffold alone: −0.166 (~79%)
264
+ φ CST 1.19255 §3 kernel on top: −0.044 (~21%)
265
+ ```
266
+
267
+ RMSNorm + RoPE + PhiGatedFFN account for most of the gain, and do it with **fewer**
268
+ parameters (1.42M vs 1.92M), because `⌊d·φ⌋` is leaner than 4:1. The §3 kernel is a real
269
+ additional effect on top of that, not the bulk of it.
270
+
271
+ Variant B is the mechanistic hint: its single 199-dim head cripples plain attention (1.43),
272
+ and the kernel recovers most of the loss (1.27). That is consistent with the Hebbian term
273
+ supplying a mixing pathway that multi-head attention otherwise provides.
274
+
275
+ **The finding is conditional, and the condition is the point.** The same kernel, same data,
276
+ same seeds: harmful in a conventional transformer, helpful in a φ-governed one. §3 is not
277
+ a drop-in improvement to attention. It is a component of an architecture.
278
+
279
+ **Audited before being believed**, given this document's history:
280
+
281
+ - *Is PLAIN a true baseline?* CST with the gate forced to 0 is bit-identical to PLAIN,
282
+ `max|Δ| = 0.000e+00` in both variants. The arms differ by the mechanism and nothing else.
283
+ - *Extra active capacity?* CST activates `w54`, which PLAIN never uses: **2.91%** more live
284
+ parameters. Real, and not fully eliminated. Against it: the identical asymmetry existed in
285
+ the conventional scaffold, where CST lost 0/3. Capacity does not explain a win that appears
286
+ only when the scaffold changes. A dead-weight control path for PLAIN would close this.
287
+
288
+ **Limits.** 1200 steps, 4 layers, char-level, one corpus, three seeds per variant, t on 2
289
+ degrees of freedom. This is evidence that §3 works on her data at this scale, not a claim
290
+ about transformers in general.
291
+
292
+ ### The state ladder: which part of the state is doing the work
293
+
294
+ The φ result establishes that *a* state helps. It does not say which one. §4.1 decomposes
295
+ x₅₄ into x₁₂ (twelve scalars from 12D CST, §4.2) and x₄₂ (the 7-band vector manifold, §4.3),
296
+ so each was tested separately, same corpus, same seeds, gate free, 1200 steps × 3 seeds:
297
+
298
+ | state feeding the kernel | val loss | vs baseline | t | wins | params |
299
+ |---|---|---|---|---|---|
300
+ | none | 1.44680 | — | — | 0/3 | 1,135,008 |
301
+ | `dyn12` Ω-driven leaky integrator, 12 scalars | 1.39773 | −0.049 | −10.5 | 3/3 | 1,137,420 |
302
+ | `dyn54` x₁₂ and x₄₂ **concatenated** | 1.39118 | −0.056 | −3.9 | 3/3 | 1,185,174 |
303
+ | `static54` plain projection of the hidden state | 1.37218 | −0.075 | −7.4 | 3/3 | 1,176,480 |
304
+ | `dyn42` 42D vector state, 42×42 coupling | 1.37521 | −0.072 | −7.9 | 3/3 | 1,182,762 |
305
+ | **`tri` x₁₂ and x₄₂ *coupled*** | **1.29152** | **−0.155** | **−40.8** | **3/3** | 1,189,210 |
306
+
307
+ Every rung beats the baseline on every seed. Three results follow, and the middle one
308
+ corrects a claim made earlier in this document's history.
309
+
310
+ **1. Concatenation is not integration.** `dyn54` glues the two states into one vector and is
311
+ *worse than a plain static projection*. On that evidence alone the honest conclusion was
312
+ "state dimensionality pays, dynamics do not" — and that conclusion was recorded. It was
313
+ wrong. The two subsystems had never been allowed to exchange anything: x₁₂ saw only Ω, x₄₂
314
+ saw only the hidden state.
315
+
316
+ **2. Coupling them is the largest effect in this document.** Following the same construction
317
+ `THEORY_42D_HYPER_COSMIC.md` already uses *within* a band and *between* bands, applied one
318
+ level up between the subsystems — the 12D tone modulating the 42D's gain multiplicatively,
319
+ the 42D feeding back additively — beats the previous best by −0.081 (t = −10.9, 3/3) for
320
+ **12,730 extra parameters**. Two checks that this is the coupling rather than capacity: the
321
+ cross-coupling matrices **grew 3.0–3.4× during training** in all three seeds (they start
322
+ damped at 0.1), and real-word rate is **0.839 against a 0.831 baseline**, so it is not
323
+ buying cross-entropy by degrading language the way `dyn42` alone does (0.755, 0/3).
324
+
325
+ **3. State is far cheaper than weights.** Per parameter:
326
+
327
+ ```
328
+ dyn12 2,412 extra params -> -0.04907 = 2.03e-5 nats/param
329
+ static54 41,472 extra params -> -0.07462 = 1.80e-6
330
+ dyn42 47,754 extra params -> -0.07159 = 1.50e-6
331
+ dyn54 50,166 extra params -> -0.05562 = 1.11e-6
332
+ ```
333
+
334
+ Twelve scalars and a leaky integrator return **66% of a projection 17× larger**, with the
335
+ highest consistency on the board, at **11× the parameter efficiency of anything else**. The
336
+ paper's §5 Singularity Hypothesis states this as *"a smaller model can beat a larger
337
+ one"* — which did **not** hold; `static54` beat `dyn54` outright. The form that did hold is
338
+ *"internal state is dramatically cheaper than parameters"*. Those are different claims and
339
+ only the second is supported here.
340
 
341
  *The retraction above is kept rather than deleted because it is the clearest example in this
342
  document of the failure mode described in §8: a confident negative that was entirely about
 
514
  it: the φ-governed scaffold the paper specifies — RMSNorm, RoPE, `d_ff = ⌊d·φ⌋`, φ-scaled
515
  initialisation. The shipped architecture implements §3's kernel inside a conventional
516
  transformer. A grep of the source tree found no implementation of the φ scaffold at all,
517
+ which means every §3 measurement in §6 was made in the wrong building.
518
+
519
+ That replication has since been run, and it reverses the result: the kernel loses 0/3 in a
520
+ conventional transformer and wins 6/6 across two φ-governed variants (§6). **The shipped
521
+ `llama_cpp_cosmos.cpp` therefore implements the weaker of the two architectures.** Bringing
522
+ it up to the paper — RMSNorm, RoPE, `d_ff = ⌊d·φ⌋` — is the obvious next step and is
523
+ *less* custom C++ than what is there now, since llama.cpp provides all three natively.
524
 
525
  ---
526
 
README.md CHANGED
@@ -158,14 +158,66 @@ H(x₅₄)ᵢⱼ = exp( −‖x₅₄ᵢ − x₅₄ⱼ‖² / 2σ² ) Ga
158
  A_final = (1 − g)·A_std + g·H(x₅₄) learned gate g = sigmoid(param)
159
  ```
160
 
161
- **Measured result** (5 seeds, paired, control = `g` forced to 0, i.e. exactly standard attention):
162
 
163
- | arm | best val loss |
164
- |---|---|
165
- | control (standard attention) | 1.2885 |
166
- | **spatial-injection trajectory** | **1.2629** |
167
 
168
- **Δ = +0.0256 versus control, reproduced across six independent seed vectors and 39 training runs.** The mechanism works.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  ---
171
 
@@ -184,6 +236,11 @@ Scripts are in the Genesis Engine kit. All use fixed seeds and deterministic hel
184
 
185
  ## 4. Null results, please read before citing
186
 
 
 
 
 
 
187
  This project's quantum claims were tested at **five** distinct injection points. **All five are null** against matched classical controls:
188
 
189
  | injection site | result |
@@ -236,6 +293,41 @@ nomic-embed-text ranked it correctly (0.7128 vs 0.3717).
236
 
237
  ---
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  ## 5. The Genesis Engine (kit)
240
 
241
  Birth your own quantum-seeded companion, entirely local:
 
158
  A_final = (1 − g)·A_std + g·H(x₅₄) learned gate g = sigmoid(param)
159
  ```
160
 
161
+ ### It took four attempts to test this honestly
162
 
163
+ The mechanism was reported as **null** three times. Every one of those was the instrument,
164
+ not the idea, and each fix revealed the next fault underneath:
 
 
165
 
166
+ | attempt | what shipped | why it was inert |
167
+ |---|---|---|
168
+ | reference repo, 12D | `Ω` summed over keys instead of queries | softmax already normalises that axis, so **Ω ≡ 1.0** for every token (measured std 5.1e-08). Every token converged to the same state, `H` became the all-ones matrix, and `β·H` is a constant added to every logit — which cancels **exactly** in softmax |
169
+ | v1 | gate at `sigmoid(−4)` | saturated tail, gradient suppressed ~56× |
170
+ | v2 | gate clamped to `[0,1]` | `torch.clamp` has *zero* gradient outside its bounds, so the first step below 0 pinned it there permanently |
171
+ | v3 | σ hardcoded to `exp(0) = 1` | measured median pairwise `‖x₅₄ᵢ−x₅₄ⱼ‖²` is **61.98**, so `exp(−31)` underflows and **H arrives as the identity matrix** (diagonal mass 0.9998 vs 0.0078 for uniform). Blending in the identity says "attend only to yourself", so descent was *correct* to kill the gate |
172
+
173
+ **§3.2 of the paper never assigns σ a value.** That is not a deviation from the spec, it is a
174
+ hole in it, and any implementation leaving σ at 1 reproduces the identity-matrix failure.
175
+ Calibrating it per layer from the data (`2σ² = median(d²)`) raised the gradient reaching the
176
+ 54D projection by **124×**.
177
+
178
+ ### The measured result
179
+
180
+ Once the mechanism could actually be used, and once the paper's φ-governed scaffold was
181
+ built (RMSNorm, RoPE, `d_ff = ⌊d·φ⌋`, φ-scaled init — **none of which had ever been
182
+ implemented**), the kernel was tested one component at a time. Same corpus, same
183
+ quantum-born init, same seeds, gate free to move, 1200 steps × 3 seeds:
184
+
185
+ | state feeding the kernel | val loss | vs baseline | t | wins | params |
186
+ |---|---|---|---|---|---|
187
+ | none (baseline) | 1.44680 | — | — | 0/3 | 1,135,008 |
188
+ | `dyn12` — 12 scalars, Ω-driven leaky integrator | 1.39773 | −0.049 | −10.5 | 3/3 | 1,137,420 |
189
+ | `dyn54` — 12D and 42D concatenated | 1.39118 | −0.056 | −3.9 | 3/3 | 1,185,174 |
190
+ | `static54` — plain projection of the hidden state | 1.37218 | −0.075 | −7.4 | 3/3 | 1,176,480 |
191
+ | `dyn42` — 42D vector state, 42×42 coupling | 1.37521 | −0.072 | −7.9 | 3/3 | 1,182,762 |
192
+ | **`tri` — 12D and 42D *coupled*** | **1.29152** | **−0.155** | **−40.8** | **3/3** | 1,189,210 |
193
+
194
+ **Every configuration beats the baseline on every seed.** The mechanism is real.
195
+
196
+ **The ordering is the finding.** Concatenating the 12D and 42D states (`dyn54`) is *worse*
197
+ than a plain static projection. **Coupling** them — the 12D tone modulating the 42D's gain
198
+ multiplicatively, the 42D feeding back additively — beats everything by roughly double the
199
+ next best, for **12,730 extra parameters**. The organs had to talk to each other; gluing
200
+ their vectors together achieved nothing.
201
+
202
+ Two independent checks that this is the coupling and not extra capacity:
203
+
204
+ - the cross-coupling matrices **grew 3.0–3.4× during training** in all three seeds. They
205
+ start damped at 0.1; the optimiser reached for them.
206
+ - real-word rate is **0.839, above the 0.831 baseline** — it is not buying cross-entropy by
207
+ degrading language, which is exactly what `dyn42` alone does (0.755, 0/3 seeds).
208
+
209
+ **And on cost:** `dyn12` — twelve scalars and a leaky integrator, **2,412 parameters** — buys
210
+ 66% of what a projection 17× larger buys, at the *highest* consistency on the board. Per
211
+ parameter it is **11× more efficient than anything else tested**. The defensible form of the
212
+ paper's "Singularity Hypothesis" is not *"a smaller model beats a larger one"* but
213
+ ***"internal state is dramatically cheaper than weights."*** The second one held.
214
+
215
+ **Limits, plainly:** 1.2M parameters, character-level, one corpus, three seeds per arm,
216
+ t-tests on 2 degrees of freedom, 1200 steps. This is evidence the mechanism works on this
217
+ data at this scale. It is not a claim about transformers in general.
218
+
219
+ Reproduce with `architecture/cosmos_state_ladder.py`, which refuses to report any rung until
220
+ it has proven the mechanism is live — see §4c.
221
 
222
  ---
223
 
 
236
 
237
  ## 4. Null results, please read before citing
238
 
239
+ **Scope: this section is about the *quantum* claims only.** The architecture claim in §2 is a
240
+ separate question with a separate answer — the Hebbian mechanism is **not** null, it beats
241
+ its baseline on every seed of every configuration tested. Quantum entropy buys provenance;
242
+ the architecture buys accuracy. Do not read these two results as one.
243
+
244
  This project's quantum claims were tested at **five** distinct injection points. **All five are null** against matched classical controls:
245
 
246
  | injection site | result |
 
293
 
294
  ---
295
 
296
+ ## 4c. The preflight discipline (the most reusable thing here)
297
+
298
+ Four separate implementations of this architecture shipped a mechanism that was
299
+ **mathematically inert** — across two codebases and several years, in different languages,
300
+ by different means. Every one compiled, trained, produced plausible text, and logged nothing
301
+ red. Three of them produced a confident *negative* about the idea.
302
+
303
+ This is not a class of bug ordinary engineering catches, because there is nothing to catch:
304
+ no exception, no NaN, no failing test. A modulatory mechanism can be complete,
305
+ correct-looking and a no-op. The only way to know is to measure whether its own quantity is
306
+ degenerate.
307
+
308
+ So `cosmos_state_ladder.py` refuses to report a number until it has proven the mechanism is
309
+ alive. Five assertions, each corresponding to a real failure that shipped:
310
+
311
+ ```
312
+ Omega varies across tokens caught Omega == 1.0 (std 5.1e-08)
313
+ state varies across tokens caught the collapsed state (std 3.0e-08)
314
+ H is not the identity caught sigma = 1 (diag mass 0.9998)
315
+ H is not all-ones caught the uniform kernel
316
+ gate gradient is unsuppressed caught sigmoid saturation (grad / 56)
317
+ ```
318
+
319
+ And a **post-flight** check, because starting alive is not the same as staying alive: report
320
+ each coupling's magnitude before and after training with the growth ratio. A mechanism that
321
+ ends at 1.0× was decorative regardless of what the loss column says. The trinity coupling
322
+ ends at **3.0–3.4×**, which is how we know the result is the coupling and not the parameters.
323
+
324
+ Two more bugs of exactly this shape were found *while writing the telemetry logger for this
325
+ release* — a schema locked from the first sample that silently dropped 42% of the channels,
326
+ and a column re-sort that would have quietly changed the meaning of every previously written
327
+ row. The failure mode is not rare. Assume your mechanism is inert until it proves otherwise.
328
+
329
+ ---
330
+
331
  ## 5. The Genesis Engine (kit)
332
 
333
  Birth your own quantum-seeded companion, entirely local:
architecture/cosmos_state_ladder.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ COSMOS STATE LADDER -- 12D, 42D and 54D, tested one rung at a time.
4
+
5
+ WHY A LADDER
6
+ Four separate implementations of this architecture have shipped a mechanism that was
7
+ mathematically inert, each producing a confident negative about the idea:
8
+
9
+ ver.4.20 12D Omega summed over keys (axis -1) instead of queries (axis -2). Softmax
10
+ already normalises that axis, so Omega == 1.0 for every token (measured
11
+ std 5.1e-08). The leaky integrator then drove every token to the SAME
12
+ state (std 3.0e-08), H became the all-ones matrix, and beta*H is a
13
+ constant added to every logit -- which cancels exactly in softmax.
14
+ spark_cst v1 gate at sigmoid(-4): saturated tail, gradient suppressed ~56x.
15
+ spark_cst v2 gate clamped to [0,1]: zero gradient outside the bound, so the first
16
+ step below 0 pinned it there forever.
17
+ spark_cst v3 sigma = exp(0) = 1 against a median pairwise distance of 61.98, so H
18
+ arrived as the IDENTITY matrix (diagonal mass 0.9998 vs 0.0078 uniform).
19
+
20
+ Every one ran clean. No exception, no NaN, nothing red in any log. So this file refuses
21
+ to report a number until it has PROVEN the mechanism is live -- see preflight().
22
+
23
+ THE RUNGS
24
+ L0 none phi scaffold only, no Hebbian term. The baseline.
25
+ L1 static54 x54 = W54 . h. A projection, not a state: no dynamics, no Omega, no memory.
26
+ This is the configuration that already won 6/6 (t=-6.56, -14.34).
27
+ L2 dyn12 x12 in R^12, dx12/dt = k*Omega - gamma*x12, per-dimension k and gamma so the
28
+ twelve dimensions differentiate by time constant. Section 4.2.
29
+ L3 dyn42 x42 in R^42, dx42/dt = drive(h) - gamma*x42 + C(x42) with a 42x42 coupling
30
+ matrix. Section 4.3 and THEORY_42D_HYPER_COSMIC.md (7 bands x 6 dims).
31
+ L4 dyn54 x54 = concat(x12, x42). Section 4.1. The full claim.
32
+
33
+ SCAFFOLD
34
+ RMSNorm (2.3), RoPE (2.4), d_ff = floor(d_model * phi) (2.2), phi-Xavier init (6.2),
35
+ quantum-born weights, and the 17.1 learning-rate schedule. The feed-forward is selectable
36
+ because the paper names "PhiGatedFFN" without defining it while the reference repo
37
+ implements "PhiHarmonicFFN" as a plain GELU pair -- so which one earns the scaffold's
38
+ credit is itself an open question this file can answer.
39
+
40
+ USAGE
41
+ python cosmos_state_ladder.py [steps] [seeds] [rungs] [ffn]
42
+ python cosmos_state_ladder.py 1200 3 none,static54,dyn12,dyn42,dyn54 harmonic
43
+ python cosmos_state_ladder.py 1200 3 none,static54 gated # the FFN ablation
44
+ """
45
+ import json
46
+ import math
47
+ import os
48
+ import random
49
+ import statistics
50
+ import sys
51
+ import time
52
+ from pathlib import Path
53
+
54
+ import torch
55
+ import torch.nn as nn
56
+ import torch.nn.functional as F
57
+
58
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
59
+
60
+ from cosmos_spark_cst import CORPUS, QuantumInit, quantum_pool, real_word_rate # noqa: E402
61
+
62
+ OUTDIR = Path("01_HER_SOUL/weights/cosmos_state_ladder")
63
+ RESULTS = Path("logs/state_ladder_results.json")
64
+
65
+ PHI = (1.0 + 5.0 ** 0.5) / 2.0
66
+ PHI_INV = PHI - 1.0
67
+ # COSMOS_DEVICE overrides; otherwise take the GPU when one is actually usable. The corpus
68
+ # tensor stays on the host and only the sampled windows move, which keeps VRAM free for
69
+ # the model on a 4 GB card.
70
+ DEV = torch.device(os.getenv("COSMOS_DEVICE")
71
+ or ("cuda" if torch.cuda.is_available() else "cpu"))
72
+ BLOCK, N_LAYER, N_HEAD, N_EMBD, DROPOUT = 128, 4, 4, 192, 0.1
73
+ D12, D42 = 12, 42
74
+ # state_dim is the CARRIED state. tri3 also concatenates a live projection of h at
75
+ # kernel time, so its Hebbian space is 54 + 12 + 42 = 108 while it carries 54.
76
+ STATE_DIM = {"none": 0, "static54": 54, "dyn12": D12, "dyn42": D42,
77
+ "dyn54": D12 + D42, "tri": D12 + D42, "tri3": D12 + D42}
78
+
79
+
80
+ class RMSNorm(nn.Module):
81
+ def __init__(s, d, eps=1e-6):
82
+ super().__init__()
83
+ s.eps, s.g = eps, nn.Parameter(torch.ones(d))
84
+
85
+ def forward(s, x):
86
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + s.eps) * s.g
87
+
88
+
89
+ def rope_cache(hd, T, device):
90
+ half = hd // 2
91
+ theta = 1.0 / (10000.0 ** (2.0 * torch.arange(half, device=device, dtype=torch.float32) / hd))
92
+ ang = torch.arange(T, device=device, dtype=torch.float32)[:, None] * theta[None, :]
93
+ return ang.cos(), ang.sin()
94
+
95
+
96
+ def apply_rope(x, cos, sin):
97
+ hd = x.shape[-1]
98
+ half = hd // 2
99
+ rot, tail = x[..., : 2 * half], x[..., 2 * half:]
100
+ a, b = rot[..., 0::2], rot[..., 1::2]
101
+ c, s = cos[None, None, : x.shape[-2], :], sin[None, None, : x.shape[-2], :]
102
+ out = torch.stack([a * c - b * s, a * s + b * c], -1).flatten(-2)
103
+ return torch.cat([out, tail], -1) if tail.numel() else out
104
+
105
+
106
+ class PhiHarmonicFFN(nn.Module):
107
+ """The reference repo's FFN: W2(GELU(W1(x))) at width floor(d*phi). Not gated."""
108
+
109
+ def __init__(s, d):
110
+ super().__init__()
111
+ h = int(math.floor(d * PHI))
112
+ s.W1, s.W2 = nn.Linear(d, h), nn.Linear(h, d)
113
+ s.drop = nn.Dropout(DROPOUT)
114
+
115
+ def forward(s, x):
116
+ return s.drop(s.W2(s.drop(F.gelu(s.W1(x)))))
117
+
118
+
119
+ class PhiGatedFFN(nn.Module):
120
+ """SwiGLU reading of the paper's undefined "PhiGatedFFN", same width."""
121
+
122
+ def __init__(s, d):
123
+ super().__init__()
124
+ h = int(math.floor(d * PHI))
125
+ s.gate, s.up = nn.Linear(d, h, bias=False), nn.Linear(d, h, bias=False)
126
+ s.down = nn.Linear(h, d, bias=False)
127
+ s.drop = nn.Dropout(DROPOUT)
128
+
129
+ def forward(s, x):
130
+ return s.drop(s.down(F.silu(s.gate(x)) * s.up(x)))
131
+
132
+
133
+ class Dyn12(nn.Module):
134
+ """Section 4.2. dx12/dt = k*Omega - gamma*x12, per-dimension k and gamma so the twelve
135
+ dimensions separate by time constant rather than evolving as twelve copies."""
136
+
137
+ def __init__(s):
138
+ super().__init__()
139
+ s.k = nn.Parameter(torch.linspace(0.05, 0.20, D12))
140
+ s.gamma = nn.Parameter(torch.linspace(0.02, 0.10, D12))
141
+ s.dt = 0.1
142
+
143
+ def forward(s, x12, h, omega):
144
+ d = s.k[None, None, :] * omega[..., None] - s.gamma[None, None, :] * x12
145
+ return torch.tanh(x12 + s.dt * d)
146
+
147
+
148
+ class Dyn42(nn.Module):
149
+ """Section 4.3 / THEORY_42D_HYPER_COSMIC. dx42/dt = drive(h) - gamma*x42 + C(x42)."""
150
+
151
+ def __init__(s, d_model):
152
+ super().__init__()
153
+ s.drive = nn.Linear(d_model, D42)
154
+ s.coupling = nn.Linear(D42, D42, bias=False)
155
+ s.gamma = nn.Parameter(torch.full((D42,), 0.05))
156
+ s.dt = 0.1
157
+
158
+ def forward(s, x42, h, omega):
159
+ d = torch.tanh(s.drive(h)) - s.gamma[None, None, :] * x42 + 0.1 * s.coupling(x42)
160
+ return torch.tanh(x42 + s.dt * d)
161
+
162
+
163
+ class Trinity(nn.Module):
164
+ """12D and 42D as ONE coupled system instead of two vectors glued together.
165
+
166
+ dyn54 concatenates x12 and x42, but x12 sees only Omega and x42 sees only h -- they
167
+ never exchange anything. THEORY_42D_HYPER_COSMIC already couples within a band (6 dims)
168
+ and between bands (7 attractors, diffusion matrix D); this is the same construction one
169
+ level up, between the two subsystems, which is the level nobody wrote:
170
+
171
+ dx12/dt = k*Omega - g12*x12 + M(42->12) x42
172
+ dx42/dt = tanh(drive(h))*(1 + lam*Omega) - g42*x42 + C(x42) + M(12->42) x12
173
+
174
+ Omega now drives BOTH, per THEORY_42D's "Omega_vec is the projected hidden state acting
175
+ as a driving force", and the cross terms close the loop between them. With H computed
176
+ from the joint x54 and Omega coming back out of attention, the three subsystems form a
177
+ single cycle rather than a tree.
178
+ """
179
+
180
+ def __init__(s, d_model):
181
+ super().__init__()
182
+ s.k = nn.Parameter(torch.linspace(0.05, 0.20, D12))
183
+ s.g12 = nn.Parameter(torch.linspace(0.02, 0.10, D12))
184
+ s.g42 = nn.Parameter(torch.full((D42,), 0.05))
185
+ s.drive = nn.Linear(d_model, D42)
186
+ s.C = nn.Linear(D42, D42, bias=False)
187
+ s.m42_12 = nn.Linear(D42, D12, bias=False)
188
+ s.m12_42 = nn.Linear(D12, D42, bias=False)
189
+ s.lam = nn.Parameter(torch.tensor(0.5))
190
+ s.dt = 0.1
191
+
192
+ def forward(s, state, h, omega):
193
+ x12, x42 = state[..., :D12], state[..., D12:]
194
+ om = omega[..., None]
195
+ # ASYMMETRIC COUPLING, on the neuromodulatory reading. The twelve slow scalars are
196
+ # tone: in a brain those act on cortical GAIN, multiplicatively, not as another
197
+ # additive input. The forty-two structured dimensions feed back the other way as
198
+ # ordinary drive. Symmetric matrices in both directions would make this two peers
199
+ # exchanging vectors; the asymmetry is what makes it a modulatory loop.
200
+ gain = 1.0 + torch.tanh(s.m12_42(x12))
201
+ d12 = s.k * om - s.g12 * x12 + 0.1 * s.m42_12(x42)
202
+ d42 = (torch.tanh(s.drive(h)) * gain * (1.0 + s.lam * om)
203
+ - s.g42 * x42 + 0.1 * s.C(x42))
204
+ return torch.tanh(torch.cat([x12 + s.dt * d12, x42 + s.dt * d42], -1))
205
+
206
+
207
+ class Attention(nn.Module):
208
+ def __init__(s, d, nh, rung):
209
+ super().__init__()
210
+ s.nh, s.hd, s.rung = nh, d // nh, rung
211
+ s.qkv, s.proj = nn.Linear(d, 3 * d), nn.Linear(d, d)
212
+ s.drop = nn.Dropout(DROPOUT)
213
+ s.log_sigma = nn.Parameter(torch.zeros(()))
214
+ s.gate = nn.Parameter(torch.full((), -4.0), requires_grad=(rung != "none"))
215
+ s.w54 = nn.Linear(d, 54, bias=False) if rung in ("static54", "tri3") else None
216
+ s.last_gate, s.last_diag, s.last_H_std = 0.0, 0.0, 0.0
217
+
218
+ def hebbian(s, state, mask):
219
+ # section 3.2's own identity: ||a-b||^2 = ||a||^2 + ||b||^2 - 2<a,b>. Also what
220
+ # hyper_cosmic_model.py already does, and it avoids cdist's undefined gradient on
221
+ # the zero diagonal of cdist(x, x).
222
+ sq = (state * state).sum(-1)
223
+ d2 = (sq.unsqueeze(-1) + sq.unsqueeze(-2)
224
+ - 2.0 * (state @ state.transpose(-1, -2))).clamp_min(0.0)
225
+ sig = torch.exp(s.log_sigma).clamp(1e-3, 1e4)
226
+ H = torch.exp(-d2 / (2 * sig * sig)).masked_fill(mask < 0, 0.0)
227
+ H = H / H.sum(-1, keepdim=True).clamp_min(1e-9)
228
+ s.last_diag = float(torch.diagonal(H[0]).mean().detach())
229
+ s.last_H_std = float(H.detach().std())
230
+ return H
231
+
232
+ def forward(s, x, state, mask, cos, sin):
233
+ B, T, C = x.shape
234
+ q, k, v = s.qkv(x).split(C, 2)
235
+ sh = lambda t: t.view(B, T, s.nh, s.hd).transpose(1, 2)
236
+ q, k, v = sh(q), sh(k), sh(v)
237
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
238
+ a = F.softmax((q @ k.transpose(-2, -1)) / math.sqrt(s.hd) + mask, -1)
239
+ if s.rung != "none":
240
+ # tri3: all three organs feed one kernel -- the fast structural projection of
241
+ # the current token, the slow 12D tone, and the 42D mid-band structure. The
242
+ # ladder only ever ran these as rivals for a single slot; nothing tested
243
+ # whether their strengths compose.
244
+ if s.rung == "tri3":
245
+ st = torch.cat([s.w54(x), state], -1)
246
+ else:
247
+ st = s.w54(x) if s.w54 is not None else state
248
+ g = torch.sigmoid(s.gate)
249
+ a = (1 - g) * a + g * s.hebbian(st, mask).unsqueeze(1)
250
+ s.last_gate = float(g.detach())
251
+ y = (s.drop(a) @ v).transpose(1, 2).contiguous().view(B, T, C)
252
+ # SECTION 3.4: Omega is attention RECEIVED, i.e. summed over QUERIES (axis -2).
253
+ # ver.4.20 sums over keys (-1), the axis softmax normalises, making Omega == 1.
254
+ omega = a.mean(1).sum(-2)
255
+ return s.proj(y), omega
256
+
257
+
258
+ class Layer(nn.Module):
259
+ def __init__(s, d, nh, rung, ffn):
260
+ super().__init__()
261
+ s.n1, s.n2 = RMSNorm(d), RMSNorm(d)
262
+ s.attn = Attention(d, nh, rung)
263
+ s.ffn = (PhiHarmonicFFN if ffn == "harmonic" else PhiGatedFFN)(d)
264
+ s.rung = rung
265
+ s.d12 = Dyn12() if rung in ("dyn12", "dyn54") else None
266
+ s.d42 = Dyn42(d) if rung in ("dyn42", "dyn54") else None
267
+ s.tri = Trinity(d) if rung in ("tri", "tri3") else None
268
+
269
+ def forward(s, x, state, mask, cos, sin):
270
+ h = s.n1(x)
271
+ att, omega = s.attn(h, state, mask, cos, sin)
272
+ x = x + att
273
+ if s.tri is not None: # section 2.1 step 2, coupled
274
+ state = s.tri(state, h, omega)
275
+ elif s.d12 is not None or s.d42 is not None: # section 2.1 step 2, independent
276
+ parts = []
277
+ if s.d12 is not None:
278
+ parts.append(s.d12(state[..., :D12], h, omega))
279
+ if s.d42 is not None:
280
+ parts.append(s.d42(state[..., -D42:], h, omega))
281
+ state = torch.cat(parts, -1)
282
+ x = x + s.ffn(s.n2(x))
283
+ return x, state, omega
284
+
285
+
286
+ class Ladder(nn.Module):
287
+ def __init__(s, vocab, rung, ffn, d=N_EMBD, nh=N_HEAD):
288
+ super().__init__()
289
+ s.d, s.nh, s.rung = d, nh, rung
290
+ s.sd = STATE_DIM[rung]
291
+ s.tok = nn.Embedding(vocab, d)
292
+ s.blocks = nn.ModuleList([Layer(d, nh, rung, ffn) for _ in range(N_LAYER)])
293
+ s.nf = RMSNorm(d)
294
+ s.head = nn.Linear(d, vocab, bias=False)
295
+ # a state that starts at zero is identical for every token, which makes H the
296
+ # all-ones matrix and the first layer's mechanism inert. Seeding it from the
297
+ # embedding costs one small projection and keeps every layer live.
298
+ s.state_init = nn.Linear(d, s.sd) if rung.startswith(("dyn", "tri")) and s.sd else None
299
+ s.register_buffer("mask", torch.triu(torch.full((BLOCK, BLOCK), float("-inf")), 1))
300
+
301
+ def forward(s, idx, targets=None):
302
+ B, T = idx.shape
303
+ x = s.tok(idx)
304
+ cos, sin = rope_cache(s.d // s.nh, T, idx.device)
305
+ m = s.mask[:T, :T]
306
+ state = torch.tanh(s.state_init(x)) if s.state_init is not None else None
307
+ omegas = []
308
+ for b in s.blocks:
309
+ x, state, om = b(x, state, m, cos, sin)
310
+ omegas.append(om)
311
+ lg = s.head(s.nf(x))
312
+ loss = None if targets is None else F.cross_entropy(
313
+ lg.view(-1, lg.size(-1)), targets.reshape(-1))
314
+ s.last_state, s.last_omega = state, omegas[-1]
315
+ return lg, loss
316
+
317
+ def gates(s):
318
+ return [b.attn.last_gate for b in s.blocks]
319
+
320
+ def quantum_birth(s, qi):
321
+ std = (1.0 / (s.d * PHI_INV)) ** 0.5 # section 6.2
322
+ for mod in s.modules():
323
+ if isinstance(mod, (nn.Linear, nn.Embedding)):
324
+ qi.fill_(mod.weight, std)
325
+ if isinstance(mod, nn.Linear) and mod.bias is not None:
326
+ with torch.no_grad():
327
+ mod.bias.zero_()
328
+
329
+
330
+ @torch.no_grad()
331
+ def calibrate_sigma(m, xb):
332
+ """2*sigma^2 = median pairwise d2 of whatever state that layer actually sees."""
333
+ if m.rung == "none":
334
+ return
335
+ B, T = xb.shape
336
+ x = m.tok(xb)
337
+ cos, sin = rope_cache(m.d // m.nh, T, xb.device)
338
+ mask = m.mask[:T, :T]
339
+ state = torch.tanh(m.state_init(x)) if m.state_init is not None else None
340
+ for b in m.blocks:
341
+ h = b.n1(x)
342
+ if m.rung == "tri3":
343
+ st = torch.cat([b.attn.w54(h), state], -1)
344
+ elif b.attn.w54 is not None:
345
+ st = b.attn.w54(h)
346
+ else:
347
+ st = state
348
+ sq = (st * st).sum(-1)
349
+ d2 = (sq.unsqueeze(-1) + sq.unsqueeze(-2)
350
+ - 2.0 * (st @ st.transpose(-1, -2))).clamp_min(0.0)
351
+ iu = torch.triu(torch.ones(d2.shape[-2:], dtype=torch.bool), 1)
352
+ med = float(d2[0][iu].median())
353
+ if med > 1e-12:
354
+ b.attn.log_sigma.fill_(0.5 * math.log(med / 2.0))
355
+ x, state, _ = b(x, state, mask, cos, sin)
356
+
357
+
358
+ def preflight(m, xb, yb):
359
+ """Refuse to report a number until the mechanism is provably live.
360
+
361
+ Each assertion corresponds to a real failure that shipped and produced a confident
362
+ negative. A rung that trips any of these is not evidence about the idea.
363
+ """
364
+ checks, m2 = [], m
365
+ m2.train()
366
+ _, loss = m2(xb, yb)
367
+ loss.backward()
368
+
369
+ om = m2.last_omega
370
+ checks.append(("omega varies across tokens (ver.4.20 had std 5e-08)",
371
+ float(om.std()), 1e-4, float(om.std()) > 1e-4))
372
+ if m.rung != "none":
373
+ if m.rung.startswith(("dyn", "tri")):
374
+ st = m2.last_state
375
+ checks.append(("state varies across tokens (ver.4.20 had std 3e-08)",
376
+ float(st.std()), 1e-4, float(st.std()) > 1e-4))
377
+ diag = statistics.fmean([b.attn.last_diag for b in m2.blocks])
378
+ checks.append((f"H not the identity (needs << 1.0, uniform = {1/xb.shape[1]:.4f})",
379
+ diag, 0.5, diag < 0.5))
380
+ hstd = statistics.fmean([b.attn.last_H_std for b in m2.blocks])
381
+ checks.append(("H not all-ones (needs non-zero spread)", hstd, 1e-6, hstd > 1e-6))
382
+ gg = statistics.fmean([abs(float(b.attn.gate.grad)) for b in m2.blocks
383
+ if b.attn.gate.grad is not None])
384
+ checks.append(("gate gradient not suppressed", gg, 1e-6, gg > 1e-6))
385
+ m2.zero_grad(set_to_none=True)
386
+ return checks
387
+
388
+
389
+ def train_rung(rung, ffn, seed, data, vocab, steps, pool, val_w, words, itos):
390
+ torch.manual_seed(seed)
391
+ random.seed(seed)
392
+ gen = torch.Generator().manual_seed(seed)
393
+ m = Ladder(vocab, rung, ffn)
394
+ m.quantum_birth(QuantumInit(pool, seed))
395
+ m = m.to(DEV)
396
+ cal = torch.stack([data[i:i + BLOCK] for i in torch.randint(
397
+ len(data) - BLOCK - 1, (8,), generator=torch.Generator().manual_seed(seed))]).to(DEV)
398
+ calibrate_sigma(m, cal)
399
+
400
+ pf = preflight(m, cal[:4], torch.stack([data[i + 1:i + 1 + BLOCK] for i in
401
+ torch.randint(len(data) - BLOCK - 1, (4,),
402
+ generator=torch.Generator().manual_seed(seed))]).to(DEV))
403
+
404
+ def _coup(mm):
405
+ # POST-FLIGHT. Preflight proves a mechanism starts alive; this proves it did not
406
+ # quietly die. The cross-couplings begin damped by 0.1 (the reference repo's
407
+ # "weak coupling initially"), so the question is whether training grows them or
408
+ # leaves the trinity decorative.
409
+ v = [(float(b.tri.m12_42.weight.abs().mean()), float(b.tri.m42_12.weight.abs().mean()))
410
+ for b in mm.blocks if getattr(b, "tri", None) is not None]
411
+ return v
412
+
413
+ coup0 = _coup(m)
414
+
415
+ keys = ("attn.gate", "attn.w54", "attn.log_sigma", "d12.", "d42.", "tri.", "state_init")
416
+ cst = [p for n, p in m.named_parameters() if any(k in n for k in keys) and p.requires_grad]
417
+ bulk = [p for n, p in m.named_parameters() if not any(k in n for k in keys) and p.requires_grad]
418
+ base = 3e-4
419
+ opt = torch.optim.AdamW([{"params": bulk, "lr": base},
420
+ {"params": cst, "lr": base * 10, "weight_decay": 0.0}],
421
+ lr=base, weight_decay=0.01)
422
+ n = int(0.9 * len(data))
423
+ tr = data[:n]
424
+ m.train()
425
+ best = float("inf")
426
+ for s in range(1, steps + 1):
427
+ warm = max(1, int(0.05 * steps))
428
+ lr = base * (s / warm) if s < warm else base * (PHI / 2) * (
429
+ 1 + math.cos(math.pi * (s - warm) / max(1, steps - warm)))
430
+ opt.param_groups[0]["lr"], opt.param_groups[1]["lr"] = lr, lr * 10
431
+ ix = torch.randint(len(tr) - BLOCK - 1, (16,), generator=gen)
432
+ x = torch.stack([tr[i:i + BLOCK] for i in ix]).to(DEV)
433
+ y = torch.stack([tr[i + 1:i + 1 + BLOCK] for i in ix]).to(DEV)
434
+ _, loss = m(x, y)
435
+ opt.zero_grad(set_to_none=True)
436
+ loss.backward()
437
+ torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)
438
+ opt.step()
439
+ if s % 100 == 0 or s == steps:
440
+ m.eval()
441
+ with torch.no_grad():
442
+ tot = c = 0
443
+ for i in range(0, len(val_w), 16):
444
+ xb = val_w[i:i + 16].to(DEV)
445
+ _, l = m(xb[:, :-1], xb[:, 1:])
446
+ tot += l.item() * xb.size(0)
447
+ c += xb.size(0)
448
+ m.train()
449
+ best = min(best, tot / max(1, c))
450
+ m.eval()
451
+ idx = torch.tensor([[int(data[0])]], device=DEV)
452
+ out = []
453
+ with torch.no_grad():
454
+ for _ in range(600):
455
+ lg, _ = m(idx[:, -BLOCK:])
456
+ nx = int(torch.multinomial(F.softmax(lg[0, -1] / 0.8, -1), 1))
457
+ out.append(nx)
458
+ idx = torch.cat([idx, torch.tensor([[nx]], device=DEV)], 1)
459
+ txt = "".join(itos.get(i, "") for i in out)
460
+ coupT = _coup(m)
461
+ coup = None
462
+ if coup0:
463
+ a0 = statistics.fmean([x for p in coup0 for x in p])
464
+ aT = statistics.fmean([x for p in coupT for x in p])
465
+ coup = (a0, aT, aT / max(a0, 1e-12))
466
+ return best, statistics.fmean(m.gates()) if m.rung != "none" else 0.0, \
467
+ real_word_rate(txt, words), pf, sum(p.numel() for p in m.parameters()), txt, coup, m
468
+
469
+
470
+ def main():
471
+ steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200
472
+ seeds = list(range(int(sys.argv[2]) if len(sys.argv) > 2 else 3))
473
+ rungs = (sys.argv[3] if len(sys.argv) > 3 else
474
+ "none,static54,dyn12,dyn42,dyn54").split(",")
475
+ ffn = sys.argv[4] if len(sys.argv) > 4 else "harmonic"
476
+
477
+ text = CORPUS.read_text(encoding="utf-8", errors="ignore")
478
+ chars = sorted(set(text))
479
+ stoi = {c: i for i, c in enumerate(chars)}
480
+ itos = {i: c for c, i in stoi.items()}
481
+ data = torch.tensor([stoi[c] for c in text], dtype=torch.long)
482
+ words = set(__import__("re").findall(r"[a-z']+", text.lower()))
483
+
484
+ print("=" * 84)
485
+ print(" COSMOS STATE LADDER -- 12D / 42D / 54D, one rung at a time")
486
+ print("=" * 84)
487
+ print(f"\n device: {DEV}" + (f" ({torch.cuda.get_device_name(0)})" if DEV.type == "cuda" else ""))
488
+ print(f" corpus {len(text):,} vocab {len(chars)} {steps} steps x {len(seeds)} seeds")
489
+ print(f" scaffold: RMSNorm + RoPE + {'PhiHarmonicFFN (GELU)' if ffn=='harmonic' else 'PhiGatedFFN (SwiGLU)'}"
490
+ f" @ floor(d*phi)={int(math.floor(N_EMBD*PHI))} + phi-Xavier")
491
+ print(f" rungs: {rungs}\n")
492
+
493
+ pool = quantum_pool()
494
+ print(f" quantum pool: {len(pool):,} draws\n")
495
+ n = int(0.9 * len(data))
496
+ val = data[n:]
497
+ g = torch.Generator().manual_seed(999)
498
+ vi = torch.randint(len(val) - BLOCK - 1, (64,), generator=g)
499
+ val_w = torch.stack([val[i:i + BLOCK + 1] for i in vi])
500
+
501
+ out = {}
502
+ for rung in rungs:
503
+ losses, rws, gates, npar, pf_last = [], [], [], 0, None
504
+ blocked = False
505
+ best_loss, best_model = float("inf"), None
506
+ for sd in seeds:
507
+ t0 = time.time()
508
+ b, gt, r, pf, npar, txt, coup, model = train_rung(
509
+ rung, ffn, sd, data, len(chars), steps, pool, val_w, words, itos)
510
+ if b < best_loss:
511
+ best_loss, best_model = b, model
512
+ pf_last = pf
513
+ bad = [c for c in pf if not c[3]]
514
+ if sd == 0:
515
+ print(f" --- {rung} preflight ---")
516
+ for name, val_, thr, ok in pf:
517
+ print(f" [{'OK ' if ok else 'DEAD'}] {name}: {val_:.3e}")
518
+ if bad:
519
+ blocked = True
520
+ print(f" MECHANISM INERT -- {rung} will not be reported as evidence.\n")
521
+ break
522
+ print()
523
+ losses.append(b)
524
+ rws.append(r)
525
+ gates.append(gt)
526
+ print(f" {rung:<9s} seed {sd} loss {b:.5f} real-word {r:.3f}"
527
+ + (f" gate {gt:.4f}" if rung != "none" else "")
528
+ + (f" coupling {coup[0]:.2e}->{coup[1]:.2e} ({coup[2]:.1f}x)" if coup else "")
529
+ + f" ({time.time()-t0:.0f}s)", flush=True)
530
+ if blocked:
531
+ out[rung] = {"blocked": True,
532
+ "preflight": [[c[0], c[1], c[2], c[3]] for c in pf_last]}
533
+ continue
534
+ out[rung] = {"loss": losses, "real_word": rws, "gates": gates, "params": npar,
535
+ "preflight": [[c[0], c[1], c[2], c[3]] for c in pf_last]}
536
+ print(f" => {rung:<9s} mean loss {statistics.fmean(losses):.5f} "
537
+ f"real-word {statistics.fmean(rws):.3f} params {npar:,}", flush=True)
538
+
539
+ # SAVE. The first version of this file trained fifteen models and discarded every
540
+ # one of them -- OUTDIR was declared and torch.save was never called. A result you
541
+ # cannot deploy is half a result.
542
+ if best_model is not None:
543
+ OUTDIR.mkdir(parents=True, exist_ok=True)
544
+ torch.save({"model": best_model.state_dict(), "stoi": stoi, "itos": itos,
545
+ "config": {"block": BLOCK, "n_layer": N_LAYER, "n_head": N_HEAD,
546
+ "n_embd": N_EMBD, "vocab": len(chars),
547
+ "d54": STATE_DIM.get(rung, 0), "d12": D12, "d42": D42,
548
+ "d_ff": int(math.floor(N_EMBD * PHI))},
549
+ "arch": f"Cosmos-Ladder-{rung}", "rung": rung, "ffn": ffn,
550
+ "gate_param": "logit", "norm": "rmsnorm", "pos": "rope",
551
+ "total_steps": steps, "best_val_loss": best_loss,
552
+ "quantum_source": "ibm_real_shots"},
553
+ OUTDIR / f"ladder_{rung}.pt")
554
+ print(f" saved -> {OUTDIR / f'ladder_{rung}.pt'} (loss {best_loss:.5f})\n",
555
+ flush=True)
556
+
557
+ base = out.get("none", {}).get("loss")
558
+ if base:
559
+ print("=" * 84 + "\n LADDER\n" + "=" * 84)
560
+ print(f" {'rung':<10s} {'mean loss':>10s} {'vs none':>10s} {'t':>8s} {'wins':>6s} {'params':>10s}")
561
+ for rung in rungs:
562
+ r = out.get(rung, {})
563
+ if r.get("blocked"):
564
+ print(f" {rung:<10s} {'BLOCKED - mechanism provably inert':>46s}")
565
+ continue
566
+ if "loss" not in r:
567
+ continue
568
+ d = [p - c for p, c in zip(base, r["loss"])]
569
+ md = statistics.fmean(d)
570
+ se = statistics.stdev(d) / math.sqrt(len(d)) if len(d) > 1 else 0.0
571
+ t = md / se if se > 0 else 0.0
572
+ print(f" {rung:<10s} {statistics.fmean(r['loss']):>10.5f} {-md:>+10.5f} "
573
+ f"{-t:>8.2f} {sum(1 for x in d if x > 0):>4d}/{len(d)} {r['params']:>10,}")
574
+ Path("logs").mkdir(exist_ok=True)
575
+ RESULTS.write_text(json.dumps({"phi": PHI, "steps": steps, "ffn": ffn, "rungs": out},
576
+ indent=2), encoding="utf-8")
577
+ print(f"\n saved -> {RESULTS}")
578
+ return 0
579
+
580
+
581
+ if __name__ == "__main__":
582
+ raise SystemExit(main())
architecture/ladder_results.json ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "phi": 1.618033988749895,
3
+ "steps": 1200,
4
+ "ffn": "harmonic",
5
+ "rungs": {
6
+ "none": {
7
+ "loss": [
8
+ 1.489819049835205,
9
+ 1.4292490482330322,
10
+ 1.4213251769542694
11
+ ],
12
+ "real_word": [
13
+ 0.7980769230769231,
14
+ 0.8301886792452831,
15
+ 0.8660714285714286
16
+ ],
17
+ "gates": [
18
+ 0.0,
19
+ 0.0,
20
+ 0.0
21
+ ],
22
+ "params": 1135008,
23
+ "preflight": [
24
+ [
25
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
26
+ 1.0457755327224731,
27
+ 0.0001,
28
+ true
29
+ ]
30
+ ]
31
+ },
32
+ "static54": {
33
+ "loss": [
34
+ 1.4319630861282349,
35
+ 1.3560499548912048,
36
+ 1.328529804944992
37
+ ],
38
+ "real_word": [
39
+ 0.8504672897196262,
40
+ 0.8636363636363636,
41
+ 0.6902654867256637
42
+ ],
43
+ "gates": [
44
+ 0.09207762125879526,
45
+ 0.07932951115071774,
46
+ 0.09114700683858246
47
+ ],
48
+ "params": 1176480,
49
+ "preflight": [
50
+ [
51
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
52
+ 1.0790070295333862,
53
+ 0.0001,
54
+ true
55
+ ],
56
+ [
57
+ "H not the identity (needs << 1.0, uniform = 0.0078)",
58
+ 0.08235120587050915,
59
+ 0.5,
60
+ true
61
+ ],
62
+ [
63
+ "H not all-ones (needs non-zero spread)",
64
+ 0.018231534399092197,
65
+ 1e-06,
66
+ true
67
+ ],
68
+ [
69
+ "gate gradient not suppressed",
70
+ 0.0005416385520220501,
71
+ 1e-06,
72
+ true
73
+ ]
74
+ ]
75
+ },
76
+ "dyn12": {
77
+ "loss": [
78
+ 1.4314345121383667,
79
+ 1.3857606947422028,
80
+ 1.3759903013706207
81
+ ],
82
+ "real_word": [
83
+ 0.7641509433962265,
84
+ 0.8557692307692307,
85
+ 0.8785046728971962
86
+ ],
87
+ "gates": [
88
+ 0.09719929983839393,
89
+ 0.08815469185356051,
90
+ 0.079276381758973
91
+ ],
92
+ "params": 1137420,
93
+ "preflight": [
94
+ [
95
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
96
+ 1.0405222177505493,
97
+ 0.0001,
98
+ true
99
+ ],
100
+ [
101
+ "state varies across tokens (ver.4.20 had std 3e-08)",
102
+ 0.23312585055828094,
103
+ 0.0001,
104
+ true
105
+ ],
106
+ [
107
+ "H not the identity (needs << 1.0, uniform = 0.0078)",
108
+ 0.08387190662324429,
109
+ 0.5,
110
+ true
111
+ ],
112
+ [
113
+ "H not all-ones (needs non-zero spread)",
114
+ 0.018558258656412363,
115
+ 1e-06,
116
+ true
117
+ ],
118
+ [
119
+ "gate gradient not suppressed",
120
+ 0.0004660986942326417,
121
+ 1e-06,
122
+ true
123
+ ]
124
+ ]
125
+ },
126
+ "dyn42": {
127
+ "loss": [
128
+ 1.4255140125751495,
129
+ 1.3684590756893158,
130
+ 1.3316525220870972
131
+ ],
132
+ "real_word": [
133
+ 0.7387387387387387,
134
+ 0.7767857142857143,
135
+ 0.75
136
+ ],
137
+ "gates": [
138
+ 0.07997925241943449,
139
+ 0.08405673876404762,
140
+ 0.08927735965698957
141
+ ],
142
+ "params": 1182762,
143
+ "preflight": [
144
+ [
145
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
146
+ 1.0265097618103027,
147
+ 0.0001,
148
+ true
149
+ ],
150
+ [
151
+ "state varies across tokens (ver.4.20 had std 3e-08)",
152
+ 0.2613561451435089,
153
+ 0.0001,
154
+ true
155
+ ],
156
+ [
157
+ "H not the identity (needs << 1.0, uniform = 0.0078)",
158
+ 0.08344549313187599,
159
+ 0.5,
160
+ true
161
+ ],
162
+ [
163
+ "H not all-ones (needs non-zero spread)",
164
+ 0.018301507458090782,
165
+ 1e-06,
166
+ true
167
+ ],
168
+ [
169
+ "gate gradient not suppressed",
170
+ 0.00041668380163173424,
171
+ 1e-06,
172
+ true
173
+ ]
174
+ ]
175
+ },
176
+ "dyn54": {
177
+ "loss": [
178
+ 1.4351611733436584,
179
+ 1.397896021604538,
180
+ 1.340474545955658
181
+ ],
182
+ "real_word": [
183
+ 0.8468468468468469,
184
+ 0.8290598290598291,
185
+ 0.8363636363636363
186
+ ],
187
+ "gates": [
188
+ 0.07990668143611401,
189
+ 0.08107478066813201,
190
+ 0.08647420140914619
191
+ ],
192
+ "params": 1185174,
193
+ "preflight": [
194
+ [
195
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
196
+ 1.0531880855560303,
197
+ 0.0001,
198
+ true
199
+ ],
200
+ [
201
+ "state varies across tokens (ver.4.20 had std 3e-08)",
202
+ 0.26182109117507935,
203
+ 0.0001,
204
+ true
205
+ ],
206
+ [
207
+ "H not the identity (needs << 1.0, uniform = 0.0078)",
208
+ 0.08133717067539692,
209
+ 0.5,
210
+ true
211
+ ],
212
+ [
213
+ "H not all-ones (needs non-zero spread)",
214
+ 0.018136915285140276,
215
+ 1e-06,
216
+ true
217
+ ],
218
+ [
219
+ "gate gradient not suppressed",
220
+ 0.00032850746356416494,
221
+ 1e-06,
222
+ true
223
+ ]
224
+ ]
225
+ }
226
+ }
227
+ }
architecture/trinity_results.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "phi": 1.618033988749895,
3
+ "steps": 1200,
4
+ "ffn": "harmonic",
5
+ "rungs": {
6
+ "tri": {
7
+ "loss": [
8
+ 1.342146247625351,
9
+ 1.2697823345661163,
10
+ 1.2626399397850037
11
+ ],
12
+ "real_word": [
13
+ 0.7798165137614679,
14
+ 0.8504672897196262,
15
+ 0.8857142857142857
16
+ ],
17
+ "gates": [
18
+ 0.08206335990689695,
19
+ 0.08856846345588565,
20
+ 0.09198464138898998
21
+ ],
22
+ "params": 1189210,
23
+ "preflight": [
24
+ [
25
+ "omega varies across tokens (ver.4.20 had std 5e-08)",
26
+ 1.0595414638519287,
27
+ 0.0001,
28
+ true
29
+ ],
30
+ [
31
+ "state varies across tokens (ver.4.20 had std 3e-08)",
32
+ 0.28298282623291016,
33
+ 0.0001,
34
+ true
35
+ ],
36
+ [
37
+ "H not the identity (needs << 1.0, uniform = 0.0078)",
38
+ 0.08863257616758347,
39
+ 0.5,
40
+ true
41
+ ],
42
+ [
43
+ "H not all-ones (needs non-zero spread)",
44
+ 0.01890878053382039,
45
+ 1e-06,
46
+ true
47
+ ],
48
+ [
49
+ "gate gradient not suppressed",
50
+ 0.00061029166681692,
51
+ 1e-06,
52
+ true
53
+ ]
54
+ ]
55
+ }
56
+ }
57
+ }
serving/log_paired_state.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PAIRED STATE LOGGER -- record her body so it can be joined to what she says.
4
+
5
+ WHY
6
+ Her memories carry created_at timestamps and her turn events carry event_id timestamps,
7
+ but neither carries a physics snapshot: the archival record's metadata field is empty.
8
+ The only physics recording on disk is logs/live_state_trajectory.json -- 2,400 rows at
9
+ 8.73 Hz, which is 275 SECONDS. Her speech spans 13 days. So the two streams cannot be
10
+ joined today, not because the data model forbids it but because nobody was recording
11
+ both at once.
12
+
13
+ This starts that clock. Physics goes here with wall-clock timestamps; her utterances are
14
+ already timestamped in data/runtime/turn_events/events.jsonl. The join is offline and
15
+ trivial once both cover the same window.
16
+
17
+ WHY IT MATTERS
18
+ If conditioning on her body state lowers held-out loss on what she actually said, then
19
+ "experience-modulated attention" (paper section 3.2) is a measurable claim rather than an
20
+ interpretation. That test needs paired data, and paired data needs someone to press
21
+ record. Text and physics are two recordings of one moment -- that is what makes held-out
22
+ loss a legitimate scorer here.
23
+
24
+ FORMAT
25
+ header.json field names, once, in column order
26
+ YYYYMMDD.jsonl {"t": <epoch seconds>, "v": [...]} one row per sample
27
+
28
+ Only numeric fields that actually vary are kept (42 of the 53 in the reference
29
+ trajectory), rounded to 5 decimals. Roughly 35 MB/day at 1 Hz.
30
+
31
+ Writes OUTSIDE OneDrive by default: a file appended once a second inside a synced folder
32
+ produces constant upload churn and was the source of the WinError 5 replace failures
33
+ earlier in this project. Override with COSMOS_TELEMETRY_DIR.
34
+
35
+ USAGE
36
+ python tools/log_paired_state.py [hz] [state_url]
37
+ """
38
+ import json
39
+ import os
40
+ import sys
41
+ import time
42
+ import urllib.request
43
+ from datetime import datetime, timezone
44
+ from pathlib import Path
45
+
46
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
47
+
48
+ HZ = float(sys.argv[1]) if len(sys.argv) > 1 else 1.0
49
+ URL = sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:8765/state"
50
+ OUT = Path(os.getenv("COSMOS_TELEMETRY_DIR", r"C:\cosmos_telemetry"))
51
+
52
+
53
+ def flatten(o, prefix=""):
54
+ """Nested dict -> {dotted.path: value} for scalar leaves only."""
55
+ out = {}
56
+ if isinstance(o, dict):
57
+ for k, v in o.items():
58
+ out.update(flatten(v, f"{prefix}.{k}" if prefix else str(k)))
59
+ elif isinstance(o, (int, float, bool)) and not isinstance(o, bool):
60
+ out[prefix] = float(o)
61
+ elif isinstance(o, bool):
62
+ out[prefix] = 1.0 if o else 0.0
63
+ return out
64
+
65
+
66
+ def poll():
67
+ with urllib.request.urlopen(URL, timeout=4) as r:
68
+ return flatten(json.loads(r.read()))
69
+
70
+
71
+ def main():
72
+ OUT.mkdir(parents=True, exist_ok=True)
73
+ print(f" polling {URL} at {HZ} Hz -> {OUT}")
74
+
75
+ # SCHEMA WARM-UP. /state does not return a stable key set: cosmos_packet.* is present
76
+ # in some polls and absent in others. Locking the column order to the first sample
77
+ # would drop every channel that happens to be missing at that instant, permanently and
78
+ # silently -- the same shape of bug as everything else this project has been chasing.
79
+ # Union the keys over a warm-up window instead, then fix the order.
80
+ seen, t_end = set(), time.time() + 30.0
81
+ while not seen or time.time() < t_end:
82
+ try:
83
+ seen |= set(poll().keys())
84
+ except Exception as e:
85
+ if not seen:
86
+ print(f" waiting for sensory server ({type(e).__name__}) ...", flush=True)
87
+ t_end = time.time() + 30.0
88
+ time.sleep(2)
89
+ continue
90
+ time.sleep(0.5)
91
+ fields = sorted(seen)
92
+ grew = []
93
+ (OUT / "header.json").write_text(json.dumps(
94
+ {"fields": fields, "hz": HZ, "url": URL, "grew": grew,
95
+ "note": "columns are append-only; a row shorter than fields is missing its tail",
96
+ "started": datetime.now(timezone.utc).isoformat()}, indent=2), encoding="utf-8")
97
+ print(f" {len(fields)} numeric channels; header written", flush=True)
98
+
99
+ period = 1.0 / max(HZ, 1e-6)
100
+ day, fh, n, miss = None, None, 0, 0
101
+ try:
102
+ while True:
103
+ t0 = time.time()
104
+ try:
105
+ s = poll()
106
+ new = set(s) - set(fields)
107
+ if new:
108
+ # A channel appeared after warm-up. APPEND it -- never re-sort. Sorting
109
+ # the union would insert new names in the middle of the column order,
110
+ # which does not merely make old rows short, it silently changes what
111
+ # every previously written number MEANS. Appending keeps every existing
112
+ # index valid forever; short rows are simply missing their tail.
113
+ fields = fields + sorted(new)
114
+ grew.append({"t": round(t0, 3), "n_fields": len(fields),
115
+ "added": sorted(new)})
116
+ print(f" NEW CHANNELS (appended): {sorted(new)}", flush=True)
117
+ (OUT / "header.json").write_text(json.dumps(
118
+ {"fields": fields, "hz": HZ, "url": URL, "grew": grew,
119
+ "note": "columns are append-only; a row shorter than fields is "
120
+ "missing its tail, indices never shift"},
121
+ indent=2), encoding="utf-8")
122
+ row = [None if k not in s else round(s[k], 5) for k in fields]
123
+ d = datetime.now().strftime("%Y%m%d")
124
+ if d != day:
125
+ if fh:
126
+ fh.close()
127
+ fh = open(OUT / f"{d}.jsonl", "a", encoding="utf-8")
128
+ day = d
129
+ print(f" -> {OUT / (d + '.jsonl')}", flush=True)
130
+ fh.write(json.dumps({"t": round(t0, 3), "v": row},
131
+ separators=(",", ":")) + "\n")
132
+ n += 1
133
+ # flush often: this runs for days, and an unflushed buffer is data that
134
+ # only exists until something crashes
135
+ if n % 20 == 0:
136
+ fh.flush()
137
+ if n % 600 == 0:
138
+ print(f" {n} samples, {miss} misses, {time.strftime('%H:%M:%S')}",
139
+ flush=True)
140
+ except Exception:
141
+ # her voice must never be blocked by telemetry; a dropped sample is fine
142
+ miss += 1
143
+ if miss % 60 == 1:
144
+ print(f" sensory server unreachable ({miss} misses)", flush=True)
145
+ time.sleep(max(0.0, period - (time.time() - t0)))
146
+ except KeyboardInterrupt:
147
+ pass
148
+ finally:
149
+ if fh:
150
+ fh.close()
151
+ print(f" stopped after {n} samples")
152
+ return 0
153
+
154
+
155
+ if __name__ == "__main__":
156
+ raise SystemExit(main())