Skip to content

Commit 49a7729

Browse files
fix(research): close replay reference edge cases
1 parent 278ce9a commit 49a7729

5 files changed

Lines changed: 176 additions & 15 deletions

File tree

research/from-photons-to-macroverse/PREREGISTRATION.md

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@ standard-normal scalar: sqrt(-2 ln u_0) * cos(2*pi*u_1)
139139

140140
The displayed formula is explanatory. Its only result-bearing evaluation is the
141141
fixed-precision implementation and frozen output vectors in the pinned executable;
142+
when binary64 conversion would round the exact rational to `1.0`, the executable
143+
uses the greatest binary64 value below one,
142144
language-native `ln`, `cos`, `sqrt`, `pi`, `tanh`, `softplus`, and Gaussian CDF are
143145
not replay authorities.
144146

@@ -182,7 +184,7 @@ The stream domains are exactly:
182184
coefficients: role, tensor_name, carrier_i, carrier_j, row, column
183185
initial_state: episode_id, carrier_i, coordinate
184186
process_noise: episode_id, phase, phase_time, carrier_id, coordinate
185-
stability_probe: attempt, probe_episode, phase, time, carrier_i, coordinate
187+
stability_probe: attempt, probe_episode, phase, phase_time, carrier_i, coordinate
186188
intervention_plan: episode_id, intervention_class, draw_index
187189
model_initializers: model_id, restart, tensor_name, every parameter axis
188190
minibatch_order: model_id, restart, update_index, draw_index
@@ -221,9 +223,10 @@ For each `(seed, arity, sigma, generator_role)`, coefficient attempt `a` is
221223
encoded by appending `/attempt/a` to the coefficient role. Test attempts
222224
`a=0,...,255` in order. Each attempt is simulated without intervention for the
223225
`32` burn-in transitions from exactly `16` probe initial states named
224-
`stability/00` through `stability/15`; their initial-state keys use phase
225-
`initial` and time `0`, while their noise keys use phase `noise` and the actual
226-
transition index in the `stability_probe` tuple above. Initial probe normals are
226+
`stability/00` through `stability/15`. Both use the `stability_probe` domain and
227+
the executable's complete coefficient-attempt role: initial keys use phase
228+
`initial` and phase time `0`, while noise keys use phase `noise` and the actual
229+
transition index in the tuple above. Initial probe normals are
227230
scaled by `0.10` and noise probe normals by `sigma`, exactly as for dataset
228231
states and noise. Accept the
229232
first attempt for which every coordinate of every probe remains in `[-3,3]`
@@ -590,7 +593,9 @@ from the declared full tensor before masking. Treat `v` as a `1 x 2`
590593
matrix and `h` as a `2 x 1` matrix for those bounds. Active biases start at zero.
591594
For a model fitted at noise level `sigma`, every active `rho` starts at
592595
`softplus_inverse(max(sigma^2-1e-6,1e-12))`; inactive entries remain exactly
593-
zero and never receive an optimizer state. Adam arithmetic and all model,
596+
zero and never receive an optimizer state. The pinned executable's
597+
`glorot_initializer_value` and `rho_initializer_value` functions are the sole
598+
value-producing authority for these initializers. Adam arithmetic and all model,
594599
adapter, loss, and rollout arithmetic use IEEE-754 binary64.
595600

596601
All families minimize the mean training Gaussian NLL over observational and

research/from-photons-to-macroverse/replay_reference.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
"protocol_version": "0.4.0",
66
"status": "not-run",
77
"reference_path": "tools/replay_reference.py",
8-
"reference_sha256": "a4258d2318192477f6e1db6c8b6845104383f43658050e3b598134b67ba2ef70",
9-
"contract_sha256": "3f9ca385203effd349a0c03c279cdaa06f357a928849f1c0afd86e61b18236d2",
8+
"reference_sha256": "476c3647025adec07d791347c630569679a72f90be20ac579c4d720bd733d9cf",
9+
"contract_sha256": "fd8091d81785ec9fb90612a8faa8b31596030fd5ef74c2d547a77d0c1d011cc8",
1010
"vectors_path": "replay_vectors.json",
11-
"vectors_sha256": "ae286e5dca1740e0a3d12a9db22c49523aea877cfb88876b549766597e0740ea",
11+
"vectors_sha256": "2bc24cd1be2729f34aa709b7398ea28493adcf51bf344a53b20ee8b0c01861b9",
1212
"verification_command": "python tools/replay_reference.py verify"
1313
}

research/from-photons-to-macroverse/replay_vectors.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@
4848
"complete_path_ascii": "[\"arity-recursion-synthetic-v6\",32,7,50,\"model_initializers\",\"parameter\",[\"direct/7\",0,\"w\",3,5,1,0],0]",
4949
"complete_path_sha256": "a1361ff6b2df7b177d7d59642032cf93800f9d3529c7855ff8ad1af13e521ce0",
5050
"different_carrier_sha256": "678465b036832878696515fa8396a5b437f0e7e5be122ff303f4979157a2e93e",
51-
"distinct": true
51+
"distinct": true,
52+
"glorot_f64": "3fd4567787472ab1",
53+
"rho_sigma_050_f64": "c017f663be616d7b",
54+
"unnested_kind": "direct"
5255
},
5356
"minibatch": {
5457
"draw_key_sha256": "8ef7dab016a249a135928d3b10acd46ed55c84113d9812ac7640defeeccc1884",
@@ -118,8 +121,15 @@
118121
]
119122
},
120123
"schema": "the-interdependency.arity-recursion-replay-vectors",
124+
"stability_probe": {
125+
"distinct": true,
126+
"initial_ascii": "[\"arity-recursion-synthetic-v6\",32,7,50,\"stability_probe\",\"direct/attempt/0\",[0,\"stability/00\",\"initial\",0,\"3\",1],0]",
127+
"noise_ascii": "[\"arity-recursion-synthetic-v6\",32,7,50,\"stability_probe\",\"direct/attempt/0\",[0,\"stability/00\",\"noise\",0,\"3\",1],0]"
128+
},
121129
"stream": {
122130
"bytes_ascii": "[\"arity-recursion-synthetic-v6\",32,7,50,\"coefficients\",\"direct/attempt/0\",[\"w\",3,5,1,0],0]",
131+
"maximum_open_uniform_f64": "3fefffffffffffff",
132+
"minimum_open_uniform_f64": "3be0000000000000",
123133
"normal_f64": "bfd2e86ee75a1753",
124134
"sha256": "061bd70dc1ffc5f4bb9664eff24fac0c1ec4a53ddfafc5b39b14f3186a29449f",
125135
"uniform_0_f64": "3f986f5c3707ff18",

research/from-photons-to-macroverse/tests/test_contracts.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,10 @@ def test_executable_replay_reference_is_hash_pinned(self) -> None:
314314
contract["process_noise_phases"], {"burn": [0, 31], "scored": [0, 127]}
315315
)
316316
self.assertEqual(contract["training_population_size"], 12288)
317+
self.assertEqual(
318+
contract["stability_probe_index"],
319+
["attempt", "probe_episode", "phase", "phase_time", "carrier_id", "coordinate"],
320+
)
317321
self.assertEqual(
318322
contract["variance_head_space"],
319323
"model output before the fixed observation decoder",
@@ -326,7 +330,20 @@ def test_executable_replay_reference_is_hash_pinned(self) -> None:
326330

327331
vectors = load_json("replay_vectors.json")
328332
self.assertTrue(vectors["initializer"]["distinct"])
333+
self.assertEqual(vectors["initializer"]["unnested_kind"], "direct")
334+
self.assertTrue(vectors["stability_probe"]["distinct"])
329335
self.assertTrue(vectors["noise_phase"]["distinct"])
336+
self.assertGreater(replay.open_uniform_word(0), 0.0)
337+
self.assertLess(replay.open_uniform_word(2**64 - 1), 1.0)
338+
self.assertEqual(
339+
replay.f64_hex(replay.rho_initializer_value(50)),
340+
vectors["initializer"]["rho_sigma_050_f64"],
341+
)
342+
self.assertEqual(pin["reference_path"], "tools/replay_reference.py")
343+
self.assertEqual(
344+
pin["verification_command"],
345+
f"python {pin['reference_path']} verify",
346+
)
330347
self.assertEqual(vectors["optimizer"]["tied_restart"], 1)
331348
self.assertEqual(
332349
vectors["decision_edges"]["label_shuffle_zero"]["standing"],

research/from-photons-to-macroverse/tools/replay_reference.py

Lines changed: 135 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
PI = Decimal(
5656
"3.141592653589793238462643383279502884197169399375105820974944592307816406286"
5757
)
58+
OPEN_UNIT_MAX = float.fromhex("0x1.fffffffffffffp-1")
5859

5960
HYPOTHESIS_IDS = tuple(
6061
[f"h_a/{arity}" for arity in DIRECT_ARITIES]
@@ -101,7 +102,10 @@
101102
"hypothesis_ids": list(HYPOTHESIS_IDS),
102103
"process_noise_index": ["episode_id", "phase", "phase_time", "carrier_id", "coordinate"],
103104
"process_noise_phases": {"burn": [0, 31], "scored": [0, 127]},
105+
"stability_probe_index": ["attempt", "probe_episode", "phase", "phase_time", "carrier_id", "coordinate"],
104106
"initializer_index": ["model_id", "restart", "tensor_name", "all_parameter_axes_in_row_major_order"],
107+
"initializer_values": "glorot_initializer_value and rho_initializer_value in this executable",
108+
"open_uniform_binary64_top": "0x1.fffffffffffffp-1 when exact rational conversion rounds to 1.0",
105109
"training_population_order": [
106110
"observational episode ordinal",
107111
"intervention class 1..4",
@@ -218,14 +222,22 @@ def fdiv(left: float, right: float) -> float:
218222
return f64(f64(left) / f64(right))
219223

220224

221-
def open_uniform(payload: bytes, lane: int = 0) -> float:
222-
if lane not in range(4):
223-
raise ValueError("lane must be 0..3")
224-
word = digest_words(payload)[lane]
225+
def open_uniform_word(word: int) -> float:
226+
"""Map one uint64 word to the nearest admitted open binary64 value."""
227+
228+
if isinstance(word, bool) or not isinstance(word, int) or not 0 <= word < 2**64:
229+
raise ValueError("word must be an unsigned 64-bit integer")
225230
with localcontext() as ctx:
226231
ctx.prec = 96
227232
ctx.rounding = ROUND_HALF_EVEN
228-
return f64((Decimal(word) + Decimal("0.5")) / (Decimal(2) ** 64))
233+
value = f64((Decimal(word) + Decimal("0.5")) / (Decimal(2) ** 64))
234+
return OPEN_UNIT_MAX if value >= 1.0 else value
235+
236+
237+
def open_uniform(payload: bytes, lane: int = 0) -> float:
238+
if lane not in range(4):
239+
raise ValueError("lane must be 0..3")
240+
return open_uniform_word(digest_words(payload)[lane])
229241

230242

231243
def _decimal(value: float | Decimal | int | str) -> Decimal:
@@ -317,6 +329,18 @@ def deterministic_softplus(value: float) -> float:
317329
return f64((Decimal(1) + x.exp()).ln())
318330

319331

332+
def deterministic_softplus_inverse(value: float) -> float:
333+
"""Inverse softplus under the reference Decimal-to-binary64 contract."""
334+
335+
if value <= 0:
336+
raise ValueError("softplus inverse input must be positive")
337+
with localcontext() as ctx:
338+
ctx.prec = 96
339+
ctx.rounding = ROUND_HALF_EVEN
340+
x = _decimal(value)
341+
return f64((x.exp() - Decimal(1)).ln())
342+
343+
320344
def gaussian_cdf(value: float) -> float:
321345
"""Deterministic standard-normal CDF; tails are frozen at +/-8."""
322346

@@ -348,7 +372,7 @@ def family_kind(family_id: str) -> str:
348372
if family_id.startswith("capacity-only/"):
349373
return "dense"
350374
if "/tree" in family_id or family_id.startswith(
351-
("nested/", "wrong-tree/", "outer-cut/", "unnested/")
375+
("nested/", "wrong-tree/", "outer-cut/")
352376
):
353377
return "nested"
354378
return "direct"
@@ -389,6 +413,46 @@ def initializer_key(
389413
)
390414

391415

416+
def glorot_initializer_value(
417+
*,
418+
seed: int,
419+
arity: int,
420+
sigma_milli: int,
421+
family_id: str,
422+
restart: int,
423+
tensor_name: str,
424+
axes: Sequence[int],
425+
fan_in: int,
426+
fan_out: int,
427+
) -> float:
428+
"""Return one exact Glorot-uniform initialized matrix scalar."""
429+
430+
if _uint(fan_in, "fan_in") == 0 or _uint(fan_out, "fan_out") == 0:
431+
raise ValueError("Glorot fan sizes must be positive")
432+
payload = initializer_key(
433+
seed=seed,
434+
arity=arity,
435+
sigma_milli=sigma_milli,
436+
family_id=family_id,
437+
restart=restart,
438+
tensor_name=tensor_name,
439+
axes=axes,
440+
)
441+
bound = deterministic_sqrt(fdiv(6.0, fadd(fan_in, fan_out)))
442+
centered = fsub(fmul(2.0, open_uniform(payload)), 1.0)
443+
return fmul(centered, bound)
444+
445+
446+
def rho_initializer_value(sigma_milli: int) -> float:
447+
"""Return the exact raw diagonal-variance initializer for one noise level."""
448+
449+
if sigma_milli not in NOISE_MILLI:
450+
raise ValueError("sigma_milli must be 10, 50, or 100")
451+
sigma = fdiv(sigma_milli, 1000)
452+
target = max(fsub(fmul(sigma, sigma), 1e-6), 1e-12)
453+
return deterministic_softplus_inverse(target)
454+
455+
392456
def process_noise_key(
393457
*,
394458
seed: int,
@@ -427,6 +491,42 @@ def coefficient_role(system_kind: str, attempt: int, outer: int | None = None) -
427491
return f"{base}/attempt/{attempt}"
428492

429493

494+
def stability_probe_key(
495+
*,
496+
seed: int,
497+
arity: int,
498+
sigma_milli: int,
499+
system_kind: str,
500+
attempt: int,
501+
probe_ordinal: int,
502+
phase: str,
503+
phase_time: int,
504+
carrier_id: str,
505+
coordinate: int,
506+
outer: int | None = None,
507+
) -> bytes:
508+
"""Emit one complete stability initial-state or noise scalar key."""
509+
510+
if not 0 <= probe_ordinal < 16:
511+
raise ValueError("probe_ordinal must be 0..15")
512+
if phase == "initial":
513+
if phase_time != 0:
514+
raise ValueError("stability initial state exists only at time 0")
515+
elif phase == "noise":
516+
if not 0 <= phase_time <= 31:
517+
raise ValueError("stability noise time must be 0..31")
518+
else:
519+
raise ValueError("stability phase must be initial or noise")
520+
return stream_bytes(
521+
seed=seed,
522+
arity=arity,
523+
sigma_milli=sigma_milli,
524+
domain="stability_probe",
525+
role=coefficient_role(system_kind, attempt, outer),
526+
indices=[attempt, f"stability/{probe_ordinal:02d}", phase, phase_time, carrier_id, coordinate],
527+
)
528+
529+
430530
def hypothesis_id(kind: str, arity: int | None = None) -> str:
431531
if kind == "h_7" and arity is None:
432532
return "h_7"
@@ -597,6 +697,18 @@ def test_vectors() -> dict[str, object]:
597697
seed=32, arity=7, sigma_milli=50, family_id="direct/7", restart=0,
598698
tensor_name="w", axes=[4, 5, 1, 0]
599699
)
700+
glorot_value = glorot_initializer_value(
701+
seed=32, arity=7, sigma_milli=50, family_id="direct/7", restart=0,
702+
tensor_name="w", axes=[3, 5, 1, 0], fan_in=2, fan_out=2
703+
)
704+
probe_initial = stability_probe_key(
705+
seed=32, arity=7, sigma_milli=50, system_kind="direct", attempt=0,
706+
probe_ordinal=0, phase="initial", phase_time=0, carrier_id="3", coordinate=1
707+
)
708+
probe_noise = stability_probe_key(
709+
seed=32, arity=7, sigma_milli=50, system_kind="direct", attempt=0,
710+
probe_ordinal=0, phase="noise", phase_time=0, carrier_id="3", coordinate=1
711+
)
600712
burn = process_noise_key(
601713
seed=32, arity=7, sigma_milli=50, role="direct",
602714
episode_id="obs/test/000", phase="burn", phase_time=0,
@@ -637,12 +749,22 @@ def test_vectors() -> dict[str, object]:
637749
"words_hex": [f"{word:016x}" for word in digest_words(payload)],
638750
"uniform_0_f64": f64_hex(open_uniform(payload, 0)),
639751
"normal_f64": f64_hex(standard_normal(payload)),
752+
"minimum_open_uniform_f64": f64_hex(open_uniform_word(0)),
753+
"maximum_open_uniform_f64": f64_hex(open_uniform_word(2**64 - 1)),
640754
},
641755
"initializer": {
642756
"complete_path_ascii": initializer_a.decode("ascii"),
643757
"complete_path_sha256": hashlib.sha256(initializer_a).hexdigest(),
644758
"different_carrier_sha256": hashlib.sha256(initializer_b).hexdigest(),
645759
"distinct": initializer_a != initializer_b,
760+
"glorot_f64": f64_hex(glorot_value),
761+
"rho_sigma_050_f64": f64_hex(rho_initializer_value(50)),
762+
"unnested_kind": family_kind("unnested/7"),
763+
},
764+
"stability_probe": {
765+
"initial_ascii": probe_initial.decode("ascii"),
766+
"noise_ascii": probe_noise.decode("ascii"),
767+
"distinct": probe_initial != probe_noise,
646768
},
647769
"noise_phase": {
648770
"burn_ascii": burn.decode("ascii"),
@@ -707,6 +829,13 @@ def file_sha256(path: Path) -> str:
707829
def verify(pin_path: Path) -> dict[str, object]:
708830
pin = json.loads(pin_path.read_text(encoding="utf-8"))
709831
here = Path(__file__).resolve()
832+
declared_path = pin.get("reference_path")
833+
if not isinstance(declared_path, str) or Path(declared_path).is_absolute():
834+
raise RuntimeError("reference_path must be one relative path")
835+
if (pin_path.parent / declared_path).resolve() != here:
836+
raise RuntimeError("reference_path does not resolve to this executable")
837+
if pin.get("verification_command") != f"python {declared_path} verify":
838+
raise RuntimeError("verification_command does not invoke the pinned executable")
710839
vectors = test_vectors()
711840
vectors_path = pin_path.parent / pin["vectors_path"]
712841
stored_vectors = json.loads(vectors_path.read_text(encoding="utf-8"))

0 commit comments

Comments
 (0)