AbstractPhil commited on
Commit
83d5fec
·
verified ·
1 Parent(s): 7e7029a

Upload beatrix_v3_colab.ipynb

Browse files
Files changed (1) hide show
  1. mini-beatrix-3/beatrix_v3_colab.ipynb +1007 -0
mini-beatrix-3/beatrix_v3_colab.ipynb ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# mini-beatrix-3 — the v3 routine (steering-and-arms craft)\n",
8
+ "\n",
9
+ "**Craft**: `mini-beatrix-3` — d1024 × L`DEPTH` (32 by the lead's ruling of 2026-09-19; the sizing range was 24-28), ctx 4096, a governed CausalSplatHUB in **every** block\n",
10
+ "(4 books × 64 anchors @ D128, supply 0.5×D), 3 banks @ ff1024, head 256@256. ~300–350M params.\n",
11
+ "Plan of record: claude-mind `history/plans/2026-09-15_beatrix_v3_plan_v2.md` (S1–S14, register A1–E, routine §4) ·\n",
12
+ "recipe `history/plans/2026-09-12_v3_recipe_v0.md` (terms A–P) · pre-flight `history/dockets/2026-09-05_bytelex_plan/v3_preflight_needs_2026-09-19.md`.\n",
13
+ "\n",
14
+ "**What this notebook is**: the v2 mission notebook re-aligned to the v3 plan. Its settings are TOGGLES set by the research,\n",
15
+ "the testing and the design — each value in C1 carries its source and names the test that would move it. What is not yet\n",
16
+ "built or measured is stated as such and gates the run exactly where the design says (the data plane before the start; the\n",
17
+ "lawful arm geometry before the first stage arm; the anneal multiplier before the anneal). The toy switch (`LOCAL = True`)\n",
18
+ "runs the whole notebook on a CPU-sized craft so the plumbing is exercised end to end.\n",
19
+ "\n",
20
+ "**Laws embodied** (all on record): supply K ≤ 2·D per book · governor from birth (min-sep, post-step, identity when slack) ·\n",
21
+ "Muon + pure Adam wd 0, never AdamW · flat LR after a 200-step warmup (the anneal's multiplier is the lead's) · bf16-train /\n",
22
+ "fp8-ship / never fp16 · eager on Blackwell (compile retired by measurement 2026-08-26) · crash-safe resume-first ·\n",
23
+ "per-boundary report + checkpoint + arm anchors (ship-complete) · the epoch cap on every finite corpus computed BEFORE a\n",
24
+ "mix ships · every stage arm quiet (per-member abstention on off-domain rows) · a faulty arm is masked out, never a crash ·\n",
25
+ "a CERTIFIED red flag halts cleanly (archive + record + refusal to auto-resume); uncertified flags are watched, never halts.\n",
26
+ "\n",
27
+ "**Price** (canon L7, 4090-measured, RTX PRO 6000 = ESTIMATE until the Colab bench cell runs): 64.4B bytes at eager speed\n",
28
+ "≈ 13.7 days at L24, 16.4 days at L28. The 2026-08-26 ruling stands beside it (\"26 days isn't reasonable\").\n"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "metadata": {},
35
+ "outputs": [],
36
+ "source": [
37
+ "# C1 — pinned installs + THE DECISION BLOCK. RESTART RUNTIME if a version line below changes.\n",
38
+ "import os, sys\n",
39
+ "os.environ['HF_HUB_DISABLE_PROGRESS_BARS'] = '1' # a progress bar is not allowed to cost a session\n",
40
+ "os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'\n",
41
+ "%pip install -q \"datasets>=5.0.0\" \"geolip-alephllm @ git+https://github.com/AbstractEyes/alephllm@ea51ec6\"\n",
42
+ "%pip install -q \"amoe-lora @ git+https://github.com/AbstractEyes/amoe-lora@e21baea\" --no-deps\n",
43
+ "%pip install -q \"geolip-bytelex @ git+https://github.com/AbstractEyes/geolip-bytelex@e8fc82d\" --no-deps\n",
44
+ "import geolip.alephllm as A\n",
45
+ "print('geolip.alephllm', A.__version__)\n",
46
+ "assert tuple(int(x) for x in A.__version__.split('.')) >= (0, 8, 9), (\n",
47
+ " 'RESTART REQUIRED: runtime still holds the old package — Runtime > Restart, then rerun from C1')\n",
48
+ "try:\n",
49
+ " import amoe; print('amoe', amoe.__version__)\n",
50
+ "except ImportError:\n",
51
+ " print('amoe-lora NOT importable — stage arms (STAGE_ARMS) cannot attach until it is')\n",
52
+ "try:\n",
53
+ " import geolip.bytelex; print('geolip.bytelex importable (the atlas coverage audit instrument)')\n",
54
+ "except ImportError:\n",
55
+ " print('geolip-bytelex NOT importable — the coverage audit needs it')\n",
56
+ "\n",
57
+ "def _token():\n",
58
+ " try:\n",
59
+ " from google.colab import userdata\n",
60
+ " return userdata.get('HF_TOKEN')\n",
61
+ " except Exception:\n",
62
+ " return os.environ.get('HF_TOKEN')\n",
63
+ "\n",
64
+ "# ============ THE TOGGLES — set by the research, the testing and the design ============\n",
65
+ "# Every value is SET FROM THE RECORD with its source beside it, and the test that would move\n",
66
+ "# it is named. They are toggles the research varies, not a form: a mission run needs no hand\n",
67
+ "# edit here. What is NOT yet built or measured is stated as such and gates the run where the\n",
68
+ "# design says it does (Cell T prints the pre-flight status). LOCAL = the CPU toy path.\n",
69
+ "DEPTH = 32 # the lead's ruling 2026-09-19 23:5x (was 24, the floor of the sizing range 24-28): depth at scale is the question the mission answers (structure continuity, routing capacity, new contextualizations); the 0.31B depth rung could not rank depths; ~+33% wall time vs 24 on 2 x 5090 (~11.7 d vs ~8.8 d); 376M params. MOVED BY: the depth-ladder erank read (proposed 09-15, not launched).\n",
70
+ "DATA_SCALE = 4.0 # S14a: 4x the 2s schedule, counted in RAW BYTES (the recorded accounting); the fused-unit count belongs to S14b once fusion exists.\n",
71
+ "EPOCH_CAP = 2.0 # the epoch-cap LAW (curriculum.py, 2026-08-15): no finite corpus re-read more than ~2x within its stage; the audit's 4 is its warning threshold, not the law.\n",
72
+ "REBALANCE_TO = 'generators' # the 08-15 precedent: procedural generators carry the volume (to their 35% share each), then natural text; the 09:12 accounting: the 4x comes from infinite sources + generators + minted programs, the structure corpora held near 1x.\n",
73
+ "ANNEAL_LR_SCALE = 'from_screen' # the design (S3 / D1): the anneal is a LOWER-LR consolidation stage (the v2 anneal at 1.0 was a diet change and left a rigid chat shell). NO NUMBER ON RECORD (recipe term H, 0 seeds): the anneal-multiplier screen sets it; the anneal boundary does not open until a number is here (Cell T gate).\n",
74
+ "ARM_SPEC = 'LAWFUL_16x8' # the supply law K <= 2D (S-801; sizing 09-15: v3 arm codebooks must come under it). The certified ladder geometry is WIDE_1024 (8x over the law, a flagged exception). GATED BY the lawful-geometry certification below.\n",
75
+ "ARM_SPEC_CERTIFIED = False # set True by the lawful-geometry certification (L4's staged co-training cell with LAWFUL_16x8, 2 seeds); until then no stage arm attaches (Cell T gate at the first stage boundary).\n",
76
+ "STAGE_ARMS = [ # C1 / S3: each capability stage attaches its arm at its boundary and trains it under the same update; earlier arms stay trainable; every member quiet at lambda 1.0 (the template/capability constant; 2.0 = hard pools). s0 is the first-language stage (no arm). OPEN: the arm-count ceiling screen.\n",
77
+ " ('s1_perspective', 'curriculum_s1', 1.0, 1), ('s2_concept', 'curriculum_s2', 1.0, 2),\n",
78
+ " ('s3_rules', 'curriculum_s3', 1.0, 3), ('s4_arith', 'curriculum_s4', 1.0, 4),\n",
79
+ " ('s5_causal', 'curriculum_s5', 1.0, 5), ('s6_tryfail', 'curriculum_s6', 1.0, 6),\n",
80
+ " ('s7_mixed', 'curriculum_s7', 1.0, 7), ('s8_register', 'curriculum_s8', 1.0, 8)]\n",
81
+ "FUSION = None # S14b (his direction): weak-token fusion at the input plane, on the atlas plane. SCREENED 2026-09-19 (canon FS; runner 22 tag 2SL28, four fresh crafts at the 2s shape on two RTX 5090s, 0.5B matched raw bytes): the BUILT FORM of the stage (spacelike / hybrid 2.5 bits / entropy 3.0 bits unit starts from the entropy table) costs +0.117-0.124 bpb over the unfused byte trunk, gains 1.48x (not the 1.7x predicted) and moves every boundary class. None = the built form is NOT READY at this budget (Phil 2026-09-19: single-axis screens cannot refute the design); the DESIGN stands open — the atlas-weighted spatial form with caveat-aware edges (S9f) is unbuilt to spec. The STAGE stays in the library (model/fusion.py); a config dict re-enables it when the design is complete.\n",
82
+ "COVERAGE_AUDIT = 'hf://AbstractPhil/alephllm-mini-beatrix-training/mini-beatrix-3/v3_preflight/coverage_audit.json' # routine step 1 / D2 / S9: RUN 2026-09-19 12:16-12:21 (tools/btx_v3_coverage_audit.py; canon CA): 26 sources at this data plane; the union of live trigram cells 6,954; half the planned mass in 254 cells (the generators 24.7% over 16-260 cells each, tinystories 11.5% at entropy 0.00) — the shape the craft reads, no bar. None = not run (gates the start).\n",
83
+ "HEAD_BIRTH = 'revival_birth' # S-1004 (born-with-function: the solve is mandatory) + the 2s record (born-null buried 3/3; the closed-form solve at 24,860 revived it). CONFIRMED by the C7 head screen 2026-09-19 (canon HS, one seed at the v3 shape): revival at birth stays live (1.13x chance) with toggle +3.29 bpb at 1,200 steps while born-null buries (0.11x, toggle 0) and the transplanted 2s head reads +0.04; matched train loss 1.232 (revival) vs 1.247 (born-null) vs 1.251 (transplant).\n",
84
+ "HUB_GAIN = None # S5 / A3: the hub gain is an inference-certified instrument; TRAINING under it is gated on his bed word by the design itself. None = off.\n",
85
+ "THINK = DIVERSITY = CONDENSING = TOOL_ARMS = None # post-training programs (S13 / S6 / S7): design items, no routine built (the last cells).\n",
86
+ "QUIET_TRUNK_GRAD = False # the certified semantics: only the arms feel the abstention term (True = the uncertified variant).\n",
87
+ "RESUME_AFTER_HALT = False # a run halted by a certified guard continues only after the archive is read (one clearance per session).\n",
88
+ "LOCAL = False # True = the toy path: a CPU-sized craft, synthetic phases, test-sized values for the names above.\n",
89
+ "# =========================================================================================\n",
90
+ "LOCAL = LOCAL or os.environ.get('ALEPHLLM_NB_LOCAL') == '1'\n",
91
+ "CRAFT = 'mini-beatrix-3'\n",
92
+ "if LOCAL:\n",
93
+ " CRAFT = 'v3-local-toy'\n",
94
+ " TEST = dict(DEPTH=2, EPOCH_CAP=2.0, REBALANCE_TO='generators', ANNEAL_LR_SCALE=0.5, ARM_SPEC='LAWFUL_16x8', ARM_SPEC_CERTIFIED=True,\n",
95
+ " STAGE_ARMS=[('s1_toy', 'curriculum_s1', 1.0, 1), ('s2_toy', 'curriculum_s2', 1.0, 2)],\n",
96
+ " FUSION={'rule': 'spacelike', 'k_lo': 1, 'k_hi': 0}, COVERAGE_AUDIT='toy', HEAD_BIRTH='born_null') # the toy exercises the fused path (one middle block over units)\n",
97
+ " globals().update(TEST)\n",
98
+ " print('LOCAL TOY PATH: test-sized values', TEST)\n",
99
+ "\n",
100
+ "def preflight_status():\n",
101
+ " # the design's step 1 (the data plane assembled) + the tests that gate later boundaries, computed\n",
102
+ " # from the toggles above — printed by Cell T; the mission run starts only when the data-plane rows\n",
103
+ " # are complete (the toy path is exempt)\n",
104
+ " rows = [('coverage audit over the pretraining mix (D2 / S9)', COVERAGE_AUDIT is not None, 'gates the start'),\n",
105
+ " ('weak-token fusion at the input plane (S14b): the rule screened (a dict) or the unfused trunk chosen (None)', FUSION not in ('not_built', 'unscreened'), 'gates the start'),\n",
106
+ " ('lawful arm geometry certified, 2 seeds (S-801)', bool(ARM_SPEC_CERTIFIED) or not STAGE_ARMS, 'gates the first stage-arm boundary'),\n",
107
+ " ('anneal multiplier from the screen (recipe term H)', isinstance(ANNEAL_LR_SCALE, (int, float)), 'gates the anneal boundary'),\n",
108
+ " ('head birth mechanism of record (S-1004)', HEAD_BIRTH in ('revival_birth', 'born_null'), 'applies at step 0')]\n",
109
+ " print(f\"{'pre-flight item':<52}{'status':>8} {'what it gates'}\")\n",
110
+ " for name, ok, gate in rows:\n",
111
+ " print(f\"{name:<52}{('done' if ok else 'OPEN'):>8} {gate}\")\n",
112
+ " return rows\n",
113
+ "\n",
114
+ "HF_TOKEN = _token()\n",
115
+ "OUT_DIR = os.environ.get('ALEPHLLM_NB_OUT', './alephllm_runs')\n",
116
+ "import torch\n",
117
+ "DEVICE = 'cuda' if torch.cuda.is_available() and os.environ.get('ALEPHLLM_NB_CPU') != '1' else 'cpu'\n",
118
+ "print(f'craft {CRAFT} · device {DEVICE} · token {\"present\" if HF_TOKEN else \"ABSENT (local artifacts only; Cell T stays disarmed for the mission)\"}')\n"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": null,
124
+ "metadata": {},
125
+ "outputs": [],
126
+ "source": [
127
+ "# C2 (P) — PREFLIGHT: build the preset for the chosen depth, law checks, bit-exact births,\n",
128
+ "# the micro-batch LADDER bench at a fixed 262,144 tokens/step, the price line. No training.\n",
129
+ "import time, math, torch\n",
130
+ "from geolip.alephllm.presets import make_v3_preset, PRESETS, AlephLMConfig, _copy_train\n",
131
+ "from geolip.alephllm.model.alephlm import AlephLM\n",
132
+ "from geolip.alephllm.model.governor import govern_model\n",
133
+ "\n",
134
+ "p = make_v3_preset(DEPTH, data_scale=DATA_SCALE, epoch_cap=EPOCH_CAP, rebalance_to=REBALANCE_TO, name=CRAFT)\n",
135
+ "if isinstance(ANNEAL_LR_SCALE, (int, float)):\n",
136
+ " p.train.phase_lr_scale = {'anneal': float(ANNEAL_LR_SCALE)} # both anneal phases; 1.0 = the flat form verbatim\n",
137
+ "else:\n",
138
+ " print(f'anneal multiplier: {ANNEAL_LR_SCALE} — the anneal boundary stays closed until the screen sets a number (Cell T gate)')\n",
139
+ "if HEAD_BIRTH == 'revival_birth':\n",
140
+ " p.train.head_addr_frozen = True # the doctrine: the address is solved at birth, then frozen (W_s trains)\n",
141
+ "if LOCAL: # the toy craft: same laws, CPU size, synthetic phases\n",
142
+ " p.model = AlephLMConfig(name=CRAFT, d_model=64, n_layers=DEPTH, n_heads=1, context=512,\n",
143
+ " hub_layers=tuple(range(DEPTH)), hub_K=4, hub_D=8, hub_const=2, # supply 0.5xD like the mission\n",
144
+ " bank_experts=3, bank_ff=64, head_K=8, head_D=16, hub_chunk=32, hub_ckpt=0)\n",
145
+ " p.train.micro_batch, p.train.grad_accum, p.train.warmup_steps = 2, 1, 2\n",
146
+ " p.train.log_every, p.train.health_every, p.train.eval_every = 2, 4, 8\n",
147
+ " p.train.ckpt_every, p.train.tb_upload_every, p.train.val_tokens, p.train.canary_episodes = 8, 1000, 256, 4\n",
148
+ " p.curriculum = [dict(ph, dataset='synthetic', planned_tokens=4096) for ph in p.curriculum]\n",
149
+ "if isinstance(FUSION, dict): # the screened rule: the hourglass form (model/fusion.py); the unfused trunk otherwise\n",
150
+ " p.model.fusion = dict(FUSION)\n",
151
+ " if str(p.model.fusion.get('table', '')).startswith('hf://'): # the atlas table lives on the hub: fetch it once\n",
152
+ " from huggingface_hub import hf_hub_download\n",
153
+ " _owner, _repo, _path = p.model.fusion['table'][5:].split('/', 2)\n",
154
+ " p.model.fusion['table'] = hf_hub_download(f'{_owner}/{_repo}', _path, token=HF_TOKEN)\n",
155
+ " print('fusion:', p.model.fusion)\n",
156
+ "PRESETS[CRAFT] = p\n",
157
+ "ctrl = AlephLMConfig.from_dict(p.model.to_dict()); ctrl.name = CRAFT + '-control'; ctrl.hub_layers = ()\n",
158
+ "PRESETS[CRAFT + '-control'] = type(p)(model=ctrl, train=_copy_train(p.train), curriculum=[dict(x) for x in p.curriculum],\n",
159
+ " data_scale=p.data_scale, epoch_cap=p.epoch_cap, rebalance_to=p.rebalance_to)\n",
160
+ "cfg, tc = p.model, p.train\n",
161
+ "PLANNED = sum(ph['planned_tokens'] for ph in p.curriculum)\n",
162
+ "print(f\"{cfg.name}: depth {cfg.n_layers} · d {cfg.d_model} · ctx {cfg.context} · hubs {len(cfg.hub_layers)}/{cfg.n_layers} × \"\n",
163
+ " f\"{cfg.hub_const} books × {cfg.hub_K}@D{cfg.hub_D} (supply {cfg.hub_K/cfg.hub_D:.2f}×D) · planned {PLANNED/1e9:.2f}B bytes\")\n",
164
+ "for ph in p.curriculum:\n",
165
+ " print(f\" {ph['name']:<18} {ph['dataset']:<16} {ph['planned_tokens']/1e9:8.3f}B\")\n",
166
+ "assert cfg.hub_K <= 2 * cfg.hub_D, 'supply law violated — this preset should not exist'\n",
167
+ "assert tc.compile is False, 'eager on Blackwell (the 2026-08-26 law)'\n",
168
+ "torch.manual_seed(tc.seed)\n",
169
+ "model = AlephLM(cfg).to(DEVICE)\n",
170
+ "n = model.param_count(); print(f'{n/1e6:.1f}M params')\n",
171
+ "hits = govern_model(model, tc.governor_theta)\n",
172
+ "print(f'governor birth check: {hits} hits (must be 0 at mission D)' + (' — toy D, not gated' if LOCAL else ''))\n",
173
+ "assert hits == 0 or LOCAL\n",
174
+ "x = torch.randint(0, 255, (2, min(cfg.context, 256)), device=DEVICE)\n",
175
+ "with torch.no_grad(): # C6 null paths: bank + head aleph contribute exactly zero at init\n",
176
+ " a = model(x, disable_bank=True, disable_head_aleph=True).logits\n",
177
+ " b = model(x).logits\n",
178
+ " assert torch.equal(a, b), 'C6 violated — born-null paths are not null'\n",
179
+ "print('C6 null paths bit-exact at birth')\n",
180
+ "\n",
181
+ "# the ladder: micro-batch by fit at a FIXED 262,144 tokens/step (16 x 4096); the first\n",
182
+ "# rung that fits is the session's micro_batch, grad_accum follows. An arm rides the\n",
183
+ "# bench when STAGE_ARMS is non-empty (the arm's forward is part of the step it prices).\n",
184
+ "TOK_STEP = tc.micro_batch * tc.grad_accum * cfg.context\n",
185
+ "if DEVICE == 'cuda':\n",
186
+ " import platform\n",
187
+ " frac = 0.73 if platform.system() == 'Windows' else 0.98\n",
188
+ " if platform.system() == 'Windows':\n",
189
+ " print('WINDOWS (WDDM): fraction 0.73 — the ~18 GB local cap; the mission card is Linux at 0.98')\n",
190
+ " torch.cuda.set_per_process_memory_fraction(frac)\n",
191
+ " total_gb = torch.cuda.get_device_properties(0).total_memory / 2**30\n",
192
+ " abort_gb = 88 if total_gb > 90 else 0.73 * total_gb\n",
193
+ " if STAGE_ARMS:\n",
194
+ " from geolip.alephllm.train.arms import StageArm, ArmProgramConfig, StageArmProgram, LAWFUL_16x8, WIDE_1024\n",
195
+ " spec = {'LAWFUL_16x8': LAWFUL_16x8, 'WIDE_1024': WIDE_1024}[ARM_SPEC]\n",
196
+ " class _T: pass\n",
197
+ " _t = _T(); _t.raw_model = model; _t.device = DEVICE; _t._trunk_params = list(model.parameters())\n",
198
+ " prog = StageArmProgram(ArmProgramConfig(arms=[StageArm('bench', 'bench', spec=dict(spec))])).bind(_t)\n",
199
+ " prog.attach(prog.by_name['bench']); print('bench with one arm attached', spec)\n",
200
+ " model.train(); best = None\n",
201
+ " for mb in (16, 8, 4, 2, 1):\n",
202
+ " accum = max(1, TOK_STEP // (mb * cfg.context))\n",
203
+ " try:\n",
204
+ " opt_probe = torch.optim.SGD([q for q in model.parameters() if q.requires_grad], lr=0.0)\n",
205
+ " xb = torch.randint(0, 255, (mb, cfg.context), device=DEVICE)\n",
206
+ " torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize(); t0 = time.time()\n",
207
+ " for i in range(3):\n",
208
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
209
+ " out = model(xb, targets=xb)\n",
210
+ " out.loss.backward(); opt_probe.zero_grad(set_to_none=True)\n",
211
+ " torch.cuda.synchronize(); sps = (time.time() - t0) / 3\n",
212
+ " vram = torch.cuda.max_memory_allocated() / 2**30\n",
213
+ " tps = mb * cfg.context / sps\n",
214
+ " print(f'mb {mb:2d} x accum {accum:2d}: {sps:.2f}s/micro · {tps/1e3:.1f}k tok/s · peak {vram:.1f} GB' + (' OVER BUDGET' if vram > abort_gb else ''))\n",
215
+ " if vram <= abort_gb and best is None:\n",
216
+ " best = (mb, accum, tps)\n",
217
+ " del out, xb, opt_probe; torch.cuda.empty_cache()\n",
218
+ " except torch.cuda.OutOfMemoryError:\n",
219
+ " print(f'mb {mb:2d}: OOM'); torch.cuda.empty_cache()\n",
220
+ " assert best is not None, 'no rung fits — the card cannot carry this depth'\n",
221
+ " tc.micro_batch, tc.grad_accum, tps = best[0], best[1], best[2]\n",
222
+ " days = PLANNED / tps / 86400\n",
223
+ " card = torch.cuda.get_device_name(0)\n",
224
+ " label = 'MEASURED on the mission card' if total_gb > 90 else f'ESTIMATE (measured on {card}, not the mission card)'\n",
225
+ " print(f'PRICE: {PLANNED/1e9:.1f}B bytes at {tps/1e3:.1f}k tok/s = {days:.1f} days — {label}; the decision is the lead\\'s (08-26: \"26 days isn\\'t reasonable\")')\n",
226
+ "else:\n",
227
+ " print('CPU: the ladder bench and the price line need a card (skipped)')\n",
228
+ "del model; torch.cuda.empty_cache() if DEVICE == 'cuda' else None\n",
229
+ "print('PREFLIGHT PASS — the data cell, the guard cell and the push cell must pass before Cell T')\n"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": null,
235
+ "metadata": {},
236
+ "outputs": [],
237
+ "source": [
238
+ "# CARD-ONLY\n",
239
+ "# C2b — WHERE DOES THE TIME GO. Run after a restart, before committing to Cell T (needs the card).\n",
240
+ "# Splits one training step into: data / forward / backward / optimizer+governor.\n",
241
+ "import time, torch\n",
242
+ "from geolip.alephllm import get_preset\n",
243
+ "from geolip.alephllm.model.alephlm import AlephLM\n",
244
+ "from geolip.alephllm.model.governor import govern_model\n",
245
+ "from geolip.alephllm.train.optim import build_optimizers\n",
246
+ "from geolip.alephllm.data.streams import build_stream\n",
247
+ "from geolip.alephllm.data.tokenizers import build_tokenizer\n",
248
+ "import geolip.alephllm as A\n",
249
+ "print('package', A.__version__); assert tuple(int(x) for x in A.__version__.split('.')) >= (0,8,9), 'STALE RUNTIME'\n",
250
+ "p = get_preset(CRAFT); cfg, tc = p.model, p.train\n",
251
+ "torch.manual_seed(0)\n",
252
+ "m = AlephLM(cfg).cuda(); m.train()\n",
253
+ "opts = build_optimizers(m, tc.muon_lr, tc.muon_momentum, tc.adam_lr)\n",
254
+ "def sync(): torch.cuda.synchronize()\n",
255
+ "x = torch.randint(0, 255, (tc.micro_batch, cfg.context), device='cuda')\n",
256
+ "# warmup (autotune, lazy inits)\n",
257
+ "with torch.autocast('cuda', dtype=torch.bfloat16):\n",
258
+ " m(x, targets=x).loss.backward()\n",
259
+ "m.zero_grad(set_to_none=True); sync()\n",
260
+ "# (a) GPU compute, synthetic data: one full accumulation step\n",
261
+ "t0 = time.time(); tf = tb = 0.0\n",
262
+ "for _ in range(tc.grad_accum):\n",
263
+ " s = time.time()\n",
264
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
265
+ " out = m(x, targets=x)\n",
266
+ " sync(); tf += time.time() - s; s = time.time()\n",
267
+ " (out.loss / tc.grad_accum).backward(); sync(); tb += time.time() - s\n",
268
+ "s = time.time()\n",
269
+ "torch.nn.utils.clip_grad_norm_(m.parameters(), tc.grad_clip)\n",
270
+ "for o in opts: o.step()\n",
271
+ "sync(); topt = time.time() - s\n",
272
+ "s = time.time(); hits = govern_model(m, tc.governor_theta); sync(); tgov = time.time() - s\n",
273
+ "m.zero_grad(set_to_none=True)\n",
274
+ "gpu_step = time.time() - t0\n",
275
+ "print(f'GPU step (synthetic data): {gpu_step:.1f}s = fwd {tf:.1f} + bwd {tb:.1f} + opt {topt:.1f} + governor {tgov:.2f} (hits {hits})')\n",
276
+ "print(f' -> pure-compute ceiling: {tc.micro_batch*cfg.context*tc.grad_accum/gpu_step/1e3:.0f}k tok/s')\n",
277
+ "# (b) the data pipeline alone: how fast can the stream feed 2M tokens?\n",
278
+ "tok = build_tokenizer(cfg.tokenizer)\n",
279
+ "st = build_stream('wikitext-103', tok, cfg.context, tc.micro_batch, seed=1, role='train')\n",
280
+ "st.next_batch() # open/download outside the clock\n",
281
+ "n_tok = 0; s = time.time()\n",
282
+ "while n_tok < 2_000_000:\n",
283
+ " b = st.next_batch(); n_tok += b.numel()\n",
284
+ "dt = time.time() - s\n",
285
+ "print(f'stream: {n_tok/dt/1e3:.0f}k tok/s CPU -> {524288/(n_tok/dt):.1f}s of data per step if serial')\n",
286
+ "print('VERDICT: whichever line dominates the observed s/step is the bottleneck.')\n"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": null,
292
+ "metadata": {},
293
+ "outputs": [],
294
+ "source": [
295
+ "# CARD-ONLY\n",
296
+ "# C2c — THE COMPILE GATE (the gate the law names, kept as a gate). Compile is RETIRED\n",
297
+ "# on Blackwell BY MEASUREMENT (2026-08-26: NaN to the embeddings on every graph; the\n",
298
+ "# 4090 reproduced it 2026-09-19 with 488/491 non-finite gradients at 1.45x speed).\n",
299
+ "# It is not a utilization lever. Law: compile trains only if the GRAD-VECTOR parity\n",
300
+ "# below passes on the training hardware — never loss-only (loss-only gating shipped\n",
301
+ "# a NaN once). Expected result: GATE FAIL; eager stands.\n",
302
+ "import time, torch\n",
303
+ "from geolip.alephllm import get_preset\n",
304
+ "from geolip.alephllm.model.alephlm import AlephLM\n",
305
+ "p = get_preset(CRAFT); cfg, tc = p.model, p.train\n",
306
+ "torch.manual_seed(0)\n",
307
+ "m = AlephLM(cfg).cuda(); m.train()\n",
308
+ "x = torch.randint(0, 255, (tc.micro_batch, cfg.context), device='cuda')\n",
309
+ "def grads(model):\n",
310
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
311
+ " model(x, targets=x).loss.backward()\n",
312
+ " g = {n: p.grad.detach().clone() for n, p in model.named_parameters() if p.grad is not None}\n",
313
+ " model.zero_grad(set_to_none=True)\n",
314
+ " return g\n",
315
+ "g_eager = grads(m)\n",
316
+ "mc = torch.compile(m)\n",
317
+ "with torch.autocast('cuda', dtype=torch.bfloat16):\n",
318
+ " mc(x, targets=x).loss.backward() # compile warmup (slow once)\n",
319
+ "m.zero_grad(set_to_none=True)\n",
320
+ "g_comp = {}\n",
321
+ "with torch.autocast('cuda', dtype=torch.bfloat16):\n",
322
+ " mc(x, targets=x).loss.backward()\n",
323
+ "for n, prm in m.named_parameters():\n",
324
+ " if prm.grad is not None: g_comp[n] = prm.grad.detach().clone()\n",
325
+ "m.zero_grad(set_to_none=True)\n",
326
+ "bad = [(n, float((g_eager[n] - g_comp[n]).abs().max())) for n in g_eager\n",
327
+ " if not torch.isfinite(g_comp[n]).all() or\n",
328
+ " float((g_eager[n] - g_comp[n]).abs().max()) > 1e-2 * (1e-6 + float(g_eager[n].abs().max()))]\n",
329
+ "nonfinite = [n for n in g_comp if not torch.isfinite(g_comp[n]).all()]\n",
330
+ "print('non-finite compiled grads:', nonfinite[:5] if nonfinite else 'NONE')\n",
331
+ "print('parity failures (rel>1e-2):', bad[:5] if bad else 'NONE')\n",
332
+ "torch.cuda.synchronize(); t0 = time.time()\n",
333
+ "for _ in range(3):\n",
334
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
335
+ " mc(x, targets=x).loss.backward()\n",
336
+ " m.zero_grad(set_to_none=True)\n",
337
+ "torch.cuda.synchronize()\n",
338
+ "sps = (time.time() - t0) / 3\n",
339
+ "print(f'compiled micro fwd+bwd: {sps:.2f}s -> projected step ~{sps*tc.grad_accum:.0f}s '\n",
340
+ " f'({tc.micro_batch*cfg.context*tc.grad_accum/(sps*tc.grad_accum)/1e3:.0f}k tok/s)')\n",
341
+ "if not nonfinite and not bad:\n",
342
+ " print('GATE PASS — set TrainConfig.compile=True for the session (p.train.compile = True before prepare)')\n",
343
+ "else:\n",
344
+ " print('GATE FAIL — eager stands; report the lines above')\n"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "metadata": {},
351
+ "outputs": [],
352
+ "source": [
353
+ "# CARD-ONLY\n",
354
+ "# C2d — INSIDE ONE HUB: per-op forward timing on the real card. Names the slow op.\n",
355
+ "import time, torch, torch.nn.functional as F\n",
356
+ "from geolip.alephllm import get_preset\n",
357
+ "from geolip.alephllm.model.attention import CausalSplatHUB\n",
358
+ "from geolip.alephllm.model.bank import AnchoredBank\n",
359
+ "p = get_preset(CRAFT); cfg, tc = p.model, p.train\n",
360
+ "torch.manual_seed(0)\n",
361
+ "hub = CausalSplatHUB(cfg.d_model, cfg.hub_K, cfg.hub_D, cfg.tau,\n",
362
+ " chunk=cfg.hub_chunk, n_const=cfg.hub_const).cuda()\n",
363
+ "bank = AnchoredBank(cfg.d_model, cfg.bank_experts, cfg.bank_ff, cfg.tau, cfg.gate_init).cuda()\n",
364
+ "B, n, d = tc.micro_batch, cfg.context, cfg.d_model\n",
365
+ "x = torch.randn(B, n, d, device='cuda')\n",
366
+ "def t(fn, reps=3):\n",
367
+ " with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):\n",
368
+ " fn(); torch.cuda.synchronize()\n",
369
+ " s = time.time()\n",
370
+ " for _ in range(reps): fn()\n",
371
+ " torch.cuda.synchronize()\n",
372
+ " return (time.time() - s) / reps\n",
373
+ "with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):\n",
374
+ " qc, kc = hub._code_cat_qk(x); v = hub.v(x)\n",
375
+ " C = min(hub.chunk, n); pad = (-n) % C; nc = (n + pad) // C\n",
376
+ " vc = (F.pad(v, (0,0,0,pad)) if pad else v).view(B, nc, C, d)\n",
377
+ " mask = hub._mask(C, x.device, vc.dtype)\n",
378
+ " K2 = qc.shape[-1]\n",
379
+ " qv = (F.pad(qc, (0,0,0,pad)) if pad else qc).view(B, nc, C, K2)\n",
380
+ " kv = (F.pad(kc, (0,0,0,pad)) if pad else kc).view(B, nc, C, K2)\n",
381
+ " S = torch.einsum('bick,bicd->bikd', kv, vc)\n",
382
+ " L = hub._prefix(nc, qc.device, qc.dtype)\n",
383
+ " P = torch.matmul(L, S.reshape(B, nc, -1)).view_as(S)\n",
384
+ " att = torch.einsum('bick,bijk->bicj', qv, kv) * mask\n",
385
+ "rows = [\n",
386
+ " ('code_cat_qk (1 softmax)', t(lambda: hub._code_cat_qk(x))),\n",
387
+ " ('v proj ', t(lambda: hub.v(x))),\n",
388
+ " ('S einsum (write) ', t(lambda: torch.einsum('bick,bicd->bikd', kv, vc))),\n",
389
+ " ('prefix matmul P ', t(lambda: torch.matmul(L, S.reshape(B, nc, -1)))),\n",
390
+ " ('att within-chunk ', t(lambda: torch.einsum('bick,bijk->bicj', qv, kv) * mask)),\n",
391
+ " ('num read (qc.P + att.v)', t(lambda: torch.einsum('bick,bikd->bicd', qv, P) + att @ vc)),\n",
392
+ " ('FULL hub.forward ', t(lambda: hub(x))),\n",
393
+ " ('bank.forward ', t(lambda: bank(x))),\n",
394
+ "]\n",
395
+ "for name, dt in rows: print(f'{name} {dt*1e3:8.1f} ms')\n",
396
+ "d_ = dict(rows)\n",
397
+ "print(f\"-> {cfg.n_layers} layers x (hub+bank) = {(d_['FULL hub.forward '] + d_['bank.forward '])*cfg.n_layers:.1f}s per micro-forward\")\n",
398
+ "print(f'-> dtypes: qc {qc.dtype}, v {v.dtype} (bf16 expected everywhere now)')"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "execution_count": null,
404
+ "metadata": {},
405
+ "outputs": [],
406
+ "source": [
407
+ "# CARD-ONLY\n",
408
+ "# C2e — hub_chunk sweep on the real card: S/P traffic ~ 1/C, att FLOPs ~ C.\n",
409
+ "# 4090 evidence (2026-08-26): flat 256–1024 wall-clock, peak memory favors larger.\n",
410
+ "# The Blackwell rules; if a non-256 chunk wins >10%%, set p.model.hub_chunk before\n",
411
+ "# build (config field, no arch change, checkpoint-compatible).\n",
412
+ "import time, torch\n",
413
+ "from geolip.alephllm import get_preset\n",
414
+ "from geolip.alephllm.model.attention import CausalSplatHUB\n",
415
+ "p = get_preset(CRAFT); cfg, tc = p.model, p.train\n",
416
+ "torch.manual_seed(0)\n",
417
+ "x = torch.randn(tc.micro_batch, cfg.context, cfg.d_model, device='cuda')\n",
418
+ "for C in (256, 512, 768, 1024, 1536):\n",
419
+ " hub = CausalSplatHUB(cfg.d_model, cfg.hub_K, cfg.hub_D, cfg.tau,\n",
420
+ " chunk=C, n_const=cfg.hub_const).cuda()\n",
421
+ " def run():\n",
422
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
423
+ " loss = hub(x).square().mean()\n",
424
+ " loss.backward(); hub.zero_grad(set_to_none=True)\n",
425
+ " run(); torch.cuda.synchronize()\n",
426
+ " s = time.time()\n",
427
+ " for _ in range(3): run()\n",
428
+ " torch.cuda.synchronize()\n",
429
+ " print(f'chunk {C:5d}: {(time.time()-s)/3*1e3:7.1f} ms fwd+bwd/layer '\n",
430
+ " f'peak {torch.cuda.max_memory_allocated()/2**30:.1f} GB')\n",
431
+ " torch.cuda.reset_peak_memory_stats()\n",
432
+ " del hub; torch.cuda.empty_cache()"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "code",
437
+ "execution_count": null,
438
+ "metadata": {},
439
+ "outputs": [],
440
+ "source": [
441
+ "# CARD-ONLY\n",
442
+ "# C2f — THE RESIDUAL: full-model micro fwd+bwd vs the hub+bank sum, plus a\n",
443
+ "# micro_batch=8 fit/speed probe. C2d/C2e see only hub+bank; the step arithmetic\n",
444
+ "# leaves a remainder unaccounted (LayerNorms x2 per block, embed, head, loss, trainer\n",
445
+ "# overhead). This names it — and if micro 8 fits, per-micro fixed costs halve.\n",
446
+ "import time, torch\n",
447
+ "from geolip.alephllm import get_preset\n",
448
+ "from geolip.alephllm.model.alephlm import AlephLM\n",
449
+ "p = get_preset(CRAFT); cfg, tc = p.model, p.train\n",
450
+ "torch.manual_seed(0)\n",
451
+ "model = AlephLM(cfg).cuda()\n",
452
+ "model.train()\n",
453
+ "\n",
454
+ "def micro(B):\n",
455
+ " idx = torch.randint(0, 256, (B, cfg.context), device='cuda')\n",
456
+ " tgt = torch.randint(0, 256, (B, cfg.context), device='cuda')\n",
457
+ " def run():\n",
458
+ " with torch.autocast('cuda', dtype=torch.bfloat16):\n",
459
+ " out = model(idx, targets=tgt)\n",
460
+ " out.loss.backward()\n",
461
+ " model.zero_grad(set_to_none=True)\n",
462
+ " try:\n",
463
+ " run(); torch.cuda.synchronize()\n",
464
+ " torch.cuda.reset_peak_memory_stats()\n",
465
+ " s = time.time()\n",
466
+ " for _ in range(2): run()\n",
467
+ " torch.cuda.synchronize()\n",
468
+ " ms = (time.time()-s)/2*1e3\n",
469
+ " pk = torch.cuda.max_memory_allocated()/2**30\n",
470
+ " print(f'micro_batch {B}: {ms/1e3:6.2f} s fwd+bwd peak {pk:.1f} GB '\n",
471
+ " f'-> step ~{ms/1e3 * (64//B):5.1f} s at {64*cfg.context/1e3:.0f}k tok (x{64//B} micros)')\n",
472
+ " return ms\n",
473
+ " except torch.cuda.OutOfMemoryError:\n",
474
+ " print(f'micro_batch {B}: OOM'); torch.cuda.empty_cache(); return None\n",
475
+ "\n",
476
+ "m4 = micro(tc.micro_batch)\n",
477
+ "# hub+bank accounting at this chunk (from C2e's per-layer fwd+bwd + one\n",
478
+ "# recompute-fwd under ckpt) vs the measured full micro:\n",
479
+ "if m4:\n",
480
+ " print(f'-> subtract (C2e ms + C2d hub-fwd ms) x {cfg.n_layers} from the micro above:')\n",
481
+ " print(' the remainder IS the residual (LN/embed/head/loss/overhead).')\n",
482
+ "micro(8) # fits? halves per-micro fixed costs at identical tokens/step\n"
483
+ ]
484
+ },
485
+ {
486
+ "cell_type": "code",
487
+ "execution_count": null,
488
+ "metadata": {},
489
+ "outputs": [],
490
+ "source": [
491
+ "# C-DATA — THE DATA PLANE at DATA_SCALE: stage budgets, every finite corpus's epochs\n",
492
+ "# per stage BEFORE the mix ships (the epoch-cap law), the rebalance under the chosen\n",
493
+ "# rule, the cross-stage epoch column, and the coverage-audit gate. Pure computation.\n",
494
+ "from geolip.alephllm.data import curriculum as C\n",
495
+ "# every (cap, rule) pair, for the record beside the chosen one: cap = epochs allowed per finite corpus per\n",
496
+ "# stage; a rule says where a capped corpus's weight goes; \"held\" = bytes taken out of the stages and given to\n",
497
+ "# general text (the hold rule only); \"cross-stage\" = a corpus's epochs summed over the whole curriculum where\n",
498
+ "# that sum still exceeds the cap (the law is per stage; the sum is a measured fact, recorded)\n",
499
+ "print(f\" {'cap / rule':<18}{'components moved':>17}{'held':>8} cross-stage epochs over the cap\")\n",
500
+ "for cap in (2.0, 4.0):\n",
501
+ " for rule in C.REBALANCE_RULES:\n",
502
+ " s = C.scaled_curriculum(DATA_SCALE, cap, rule)\n",
503
+ " moved = [r for r in s['table'] if r[2] != r[3]]\n",
504
+ " hot = {n: e for n, e in s['cross_stage'].items() if e > cap}\n",
505
+ " mark = ' <- the record\\'s rule' if (cap == EPOCH_CAP and rule == REBALANCE_TO) else ''\n",
506
+ " print(f\" {f'{cap:g} / {rule}':<18}{len(moved):>17}{s['held_tokens']/1e9:>7.1f}B {hot or 'none'}{mark}\")\n",
507
+ "print()\n",
508
+ "sc = C.scaled_curriculum(DATA_SCALE, EPOCH_CAP, REBALANCE_TO)\n",
509
+ "print(f'scale x{DATA_SCALE:g} · cap {sc[\"epoch_cap\"]:g} epochs · rule {REBALANCE_TO} · stages '\n",
510
+ " f'{sum(sc[\"stage_tokens\"].values())/1e9:.2f}B' + (f' · held {sc[\"held_tokens\"]/1e9:.1f}B -> fineweb_main' if sc['held_tokens'] else ''))\n",
511
+ "if sc['flags']:\n",
512
+ " print('FLAGS', sc['flags'])\n",
513
+ "print(f\"{'stage':<14}{'component':<20}{'w before':>9}{'w after':>9}{'ep before':>10}{'ep after':>9}\")\n",
514
+ "for st, n, wb, wa, eb, ea in sc['table']:\n",
515
+ " mark = ' <- moved' if wb != wa else ''\n",
516
+ " print(f'{st:<14}{n:<20}{wb:>9.3f}{wa:>9.3f}{eb:>10.2f}{ea:>9.2f}{mark}')\n",
517
+ "print('cross-stage epochs (total over the curriculum):', sc['cross_stage'])\n",
518
+ "for st, mix in sc['mixes'].items():\n",
519
+ " ballast = sum(w for n, w in mix if n in C.NATURAL)\n",
520
+ " top = max([w for n, w in mix if n.endswith('-synth')], default=0.0)\n",
521
+ " assert ballast >= C.MIN_BALLAST - 1e-9, (st, ballast, 'ballast law')\n",
522
+ " assert top <= C.MAX_GENERATOR_SHARE + 1e-9, (st, top, 'generator share law')\n",
523
+ "print('ballast >= 30% and every generator <= 35% in every stage: OK')\n",
524
+ "print('NOTE: the infinite recipients (cosmo-young, fineweb-good, wikipedia-en, gutenberg) are infinite by the '\n",
525
+ " 'registry; their supply at the 4x demand is OWED a measurement (the coverage audit).')\n",
526
+ "if COVERAGE_AUDIT is None:\n",
527
+ " print('COVERAGE AUDIT: not run — the mix-level atlas audit (WeightField.caveat / coverage set-ops over N sampled rows per '\n",
528
+ " 'source) is the next data-plane build; the design\\'s step 1 is incomplete until it runs (Cell T status)')\n",
529
+ "else:\n",
530
+ " print('coverage audit report:', COVERAGE_AUDIT)\n",
531
+ "DATA_PLANE = C.data_plane(DATA_SCALE, EPOCH_CAP, REBALANCE_TO)\n",
532
+ "print('data plane fingerprint (asserted on every resume):', DATA_PLANE)\n"
533
+ ]
534
+ },
535
+ {
536
+ "cell_type": "code",
537
+ "execution_count": null,
538
+ "metadata": {},
539
+ "outputs": [],
540
+ "source": [
541
+ "# C-GUARD — THE RED-FLAG CORE from the shipped L6 certification ledger. A guard halts\n",
542
+ "# ONLY with a certification on record (fires on its own induced fault within 600 steps\n",
543
+ "# AND silent on both healthy seeds); everything else is watched. The library's census\n",
544
+ "# flags fire on healthy births — recorded, never interrupts. G4-G6 are boundary reads.\n",
545
+ "import json, os\n",
546
+ "from huggingface_hub import hf_hub_download\n",
547
+ "from geolip.alephllm.train.guards import GuardConfig, certification_from_ledger, GUARDS\n",
548
+ "from geolip.alephllm.presets import TRAINING_REPO\n",
549
+ "LEDGER_PATH = 'v3_preflight/l6_guards/v3_l6_guards_ledger.json'\n",
550
+ "led = None\n",
551
+ "for cand in ([os.environ.get('ALEPHLLM_L6_LEDGER')] if os.environ.get('ALEPHLLM_L6_LEDGER') else []):\n",
552
+ " if os.path.exists(cand):\n",
553
+ " led = json.load(open(cand, encoding='utf-8')); print('ledger (local):', cand)\n",
554
+ "if led is None:\n",
555
+ " try:\n",
556
+ " led = json.load(open(hf_hub_download(TRAINING_REPO, LEDGER_PATH, token=HF_TOKEN), encoding='utf-8'))\n",
557
+ " print('ledger (hub):', LEDGER_PATH)\n",
558
+ " except Exception as e:\n",
559
+ " print('ledger unavailable:', repr(e)[:200])\n",
560
+ "cert = certification_from_ledger(led or {})\n",
561
+ "V = (led or {}).get('verdict', {}).get('certification', {})\n",
562
+ "print(f\"{'guard':<12}{'fault':>6}{'first fire':>11}{'latency':>8}{'healthy silent':>15}{'CERTIFIED':>10}\")\n",
563
+ "for g, r in V.items():\n",
564
+ " print(f\"{g:<12}{str(r.get('fault_arm')):>6}{str(r.get('first_fire')):>11}{str(r.get('latency')):>8}\"\n",
565
+ " f\"{str(r.get('silent_on_healthy')):>15}{str(r.get('CERTIFIED')):>10}\")\n",
566
+ "if not V:\n",
567
+ " print('NO VERDICT in the ledger (the certification run has not finished, or the ledger is missing)')\n",
568
+ "print('modes:', cert['modes'])\n",
569
+ "if not any(m == 'halt' for m in cert['modes'].values()):\n",
570
+ " print('ZERO certified guards in this ledger: every guard runs in watch mode — recorded in the manifest at Cell T')\n",
571
+ "GUARD_CONFIG = GuardConfig(modes=cert['modes'], certification=cert['certification'],\n",
572
+ " census_dataset='synthetic' if LOCAL else 'fineweb-edu',\n",
573
+ " ref_window=(4, 16) if LOCAL else (1000, 2000),\n",
574
+ " census_every=4 if LOCAL else 100)\n",
575
+ "print('reference window (steps]:', GUARD_CONFIG.ref_window, '· norm sample every', 'log_every', '· census every', GUARD_CONFIG.census_every,\n",
576
+ " 'on one pinned batch from', GUARD_CONFIG.census_dataset, 'with every arm masked')\n"
577
+ ]
578
+ },
579
+ {
580
+ "cell_type": "code",
581
+ "execution_count": null,
582
+ "metadata": {},
583
+ "outputs": [],
584
+ "source": [
585
+ "# C-PUSH — THE PUSH PROBE (the ship-complete law): a write to the training repo under\n",
586
+ "# <craft>/v3_preflight/ and a read-back BEFORE any training. Tokenless = disarmed.\n",
587
+ "import json, time\n",
588
+ "from huggingface_hub import HfApi\n",
589
+ "from geolip.alephllm.presets import TRAINING_REPO\n",
590
+ "PUSH_OK = False\n",
591
+ "if HF_TOKEN:\n",
592
+ " api = HfApi(token=HF_TOKEN)\n",
593
+ " path = f'{CRAFT}/v3_preflight/push_probe.json'\n",
594
+ " body = json.dumps({'craft': CRAFT, 'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),\n",
595
+ " 'depth': DEPTH, 'data_plane': DATA_PLANE, 'modes': GUARD_CONFIG.modes}).encode()\n",
596
+ " api.upload_file(path_or_fileobj=body, path_in_repo=path, repo_id=TRAINING_REPO, commit_message='v3 push probe')\n",
597
+ " files = set(api.list_repo_files(TRAINING_REPO))\n",
598
+ " PUSH_OK = path in files\n",
599
+ " print('push probe', 'READ BACK OK' if PUSH_OK else 'NOT VISIBLE after upload', path)\n",
600
+ "else:\n",
601
+ " print('TOKENLESS: no probe written; the mission Cell T stays DISARMED (the toy path proceeds on local artifacts)')\n",
602
+ "assert PUSH_OK or LOCAL, 'Cell T needs a verified push path'\n"
603
+ ]
604
+ },
605
+ {
606
+ "cell_type": "code",
607
+ "execution_count": null,
608
+ "metadata": {},
609
+ "outputs": [],
610
+ "source": [
611
+ "# C3 (T) — THE SESSION. Resume-first; stops at stage boundaries; every boundary ships a\n",
612
+ "# checkpoint (HubSync), the arm anchors, AND a report JSON (this cell). A CERTIFIED guard\n",
613
+ "# halt returns cleanly: the position is archived under its own name, latest.pt stays at\n",
614
+ "# the last healthy checkpoint, the manifest records the halt, and the run refuses to\n",
615
+ "# continue until RESUME_AFTER_HALT is set for a session (read the archive first).\n",
616
+ "import gc, json, os, time, torch\n",
617
+ "from geolip.alephllm import prepare\n",
618
+ "from geolip.alephllm.train import probes\n",
619
+ "from geolip.alephllm.train.instruments import model_census, toggle_ledger, special_token_gauge\n",
620
+ "from geolip.alephllm.model.governor import govern_model\n",
621
+ "assert PUSH_OK or LOCAL, 'the push probe did not pass'\n",
622
+ "rows = preflight_status()\n",
623
+ "if not LOCAL and not all(ok for name, ok, gate in rows if gate == 'gates the start'):\n",
624
+ " raise SystemExit('the design\\'s pre-flight (routine step 1: the data plane assembled) is incomplete — the OPEN rows above '\n",
625
+ " 'are builds/tests on the queue, not decisions; the mission run starts when they land')\n",
626
+ "MAX_HOURS = 10.5 if not LOCAL else 0.2\n",
627
+ "\n",
628
+ "ARM_PROGRAM = None\n",
629
+ "if STAGE_ARMS:\n",
630
+ " from geolip.alephllm.train.arms import StageArm, ArmProgramConfig, StageArmProgram, LAWFUL_16x8, WIDE_1024\n",
631
+ " spec = {'LAWFUL_16x8': LAWFUL_16x8, 'WIDE_1024': WIDE_1024}[ARM_SPEC]\n",
632
+ " if spec['K'] > 2 * spec['D']:\n",
633
+ " print(f'ARM_SPEC {ARM_SPEC}: K {spec[\"K\"]} > 2D — a flagged exception to the supply law (the certified ladder geometry)')\n",
634
+ " ARM_PROGRAM = StageArmProgram(ArmProgramConfig(\n",
635
+ " arms=[StageArm(name, phase, spec=dict(spec), lam=float(lam), seed=int(seed)) for name, phase, lam, seed in STAGE_ARMS],\n",
636
+ " offdomain_dataset='synthetic' if LOCAL else 'fineweb-edu', quiet_trunk_grad=bool(QUIET_TRUNK_GRAD)))\n",
637
+ " print('stage arms:', [(a.name, a.phase, a.lam) for a in ARM_PROGRAM.cfg.arms], '· trunk-live form: 0 seeds (the v3 rung; frozen-trunk certified 2 seeds)')\n",
638
+ "\n",
639
+ "run = prepare(PRESETS[CRAFT], hf_token=HF_TOKEN, out_dir=OUT_DIR, guard=GUARD_CONFIG, arms=ARM_PROGRAM,\n",
640
+ " resume=os.environ.get('ALEPHLLM_NB_FRESH') != '1', device=DEVICE)\n",
641
+ "if run.step == 0 and HEAD_BIRTH == 'revival_birth':\n",
642
+ " # the born-with-function solve at step 0 (the C7 arm-B form): fit the head address in closed\n",
643
+ " # form on a birth sample, freeze the address, log provenance — a boundary-write at birth\n",
644
+ " from geolip.alephllm.train.revival import revive_head\n",
645
+ " m = run.raw_model.float(); hs, bl, ys = [], [], []\n",
646
+ " hook = m.nf.register_forward_hook(lambda mod, i, o: hs.append(o.detach().float().reshape(-1, o.shape[-1])))\n",
647
+ " with torch.no_grad():\n",
648
+ " for xb in run._val():\n",
649
+ " out = m(xb[:, :-1], disable_head_aleph=True)\n",
650
+ " bl.append(out.logits.float().reshape(-1, m.cfg.vocab_size)); ys.append(xb[:, 1:].reshape(-1))\n",
651
+ " hook.remove()\n",
652
+ " prov = revive_head(m, torch.cat(hs), torch.cat(bl), torch.cat(ys), theta_deg=45.0)\n",
653
+ " m.head.proj.weight.requires_grad_(False); m.head.addr.codebook.requires_grad_(False)\n",
654
+ " run.manifest.note(f'HEAD_BIRTH revival_birth at step 0: {json.dumps(prov, default=float)[:400]}')\n",
655
+ " print('head solved at birth (provenance in the manifest); address frozen; W_s trains')\n",
656
+ "elif HEAD_BIRTH == 'born_null':\n",
657
+ " run.manifest.note('HEAD_BIRTH born_null: the 2s birth form (buried 3/3 on record) — a flagged exception to S-1004')\n",
658
+ "REPORT_DIR = os.path.join(run.out_dir, 'reports', 'v3'); os.makedirs(REPORT_DIR, exist_ok=True)\n",
659
+ "_prev_anneal = {}\n",
660
+ "\n",
661
+ "def boundary_report(run, tag):\n",
662
+ " m, dev = run.raw_model, run.device\n",
663
+ " m.eval()\n",
664
+ " with torch.no_grad():\n",
665
+ " pr = probes.run_all(m, run.tokenizer, dev)\n",
666
+ " census = model_census(m, run._sample_batch()) # a VAL sample, never training rows\n",
667
+ " ledger = toggle_ledger(m, run._val())\n",
668
+ " arms = None\n",
669
+ " if run.arms is not None and run.arms.attached:\n",
670
+ " with run.arms.all_off():\n",
671
+ " bare = toggle_ledger(m, run._val())\n",
672
+ " ledger['bpb_arms_off'] = bare['bpb_full']; ledger['toggle_arms_off'] = bare['bpb_full'] - ledger['bpb_full']\n",
673
+ " arms = run.arms.gauges(run._val(), None)\n",
674
+ " sp = special_token_gauge(m, run._val())\n",
675
+ " erank = {str(L): census['layers'][L].get('hidden_erank') for L in census['layers']}\n",
676
+ " rep = {'tag': tag, 'step': run.step, 'tokens': run.manifest.tokens_seen, 'phase': tag,\n",
677
+ " 'next_phase': (run.manifest.current_phase() or {}).get('name'), 'lr_mult': run._phase_mult(tag),\n",
678
+ " 'probes': pr, 'census_flags': census.get('flags'), 'erank_profile': erank, 'ledger': ledger, 'special': sp,\n",
679
+ " 'governor_hits_cum': getattr(run, '_gov_hits', 0),\n",
680
+ " 'crowd_check_extra_hits': govern_model(m, run.tc.governor_theta) if run.tc.governor else None,\n",
681
+ " 'guard': run.guard.summary() if run.guard is not None else None, 'arms': arms,\n",
682
+ " 'arms_disabled': dict(run.arms.disabled) if run.arms is not None else None,\n",
683
+ " 'halt': run.manifest.halt}\n",
684
+ " # boundary reads G5/G6 (WATCH; no interrupt of record): G5 = a member past the quiet bar\n",
685
+ " # (+.012 fineweb) or blending (selectivity <= 1.5); G6 = termination regression across\n",
686
+ " # anneal checkpoints (doc/reset bpb rising) — recorded with fired=False until a rule is minted\n",
687
+ " if run.guard is not None:\n",
688
+ " if arms:\n",
689
+ " bad = {n: r for n, r in arms.items() if isinstance(r, dict) and (r.get('fineweb_delta', 0) > 0.012)}\n",
690
+ " run.guard.record_boundary_read('G5', tag, {'fired': False, 'step': run.step, 'past_quiet_bar': list(bad)})\n",
691
+ " if tag.startswith('anneal') and sp:\n",
692
+ " prev = _prev_anneal.get('sp')\n",
693
+ " delta = {k: sp[k] - prev[k] for k in ('doc_bpb', 'reset_bpb') if prev and k in sp and k in prev}\n",
694
+ " run.guard.record_boundary_read('G6', tag, {'fired': False, 'step': run.step, 'delta_vs_previous': delta})\n",
695
+ " _prev_anneal['sp'] = sp\n",
696
+ " if run.arms is not None:\n",
697
+ " for n in run.arms.attached:\n",
698
+ " ck = run.arms.anchor(n, CRAFT, run.step)\n",
699
+ " apath = os.path.join(run.out_dir, 'arms', f'{n}_step{run.step}.safetensors'); os.makedirs(os.path.dirname(apath), exist_ok=True)\n",
700
+ " ck.save(apath); run.hub._up(apath, f'arms/{n}_step{run.step}.safetensors')\n",
701
+ " body = json.dumps(rep, default=float)\n",
702
+ " with open(os.path.join(REPORT_DIR, f'{tag}_step{run.step}.json'), 'w', encoding='utf-8') as f:\n",
703
+ " f.write(body)\n",
704
+ " run.hub.upload_bytes(body.encode(), f'reports/v3/{tag}_step{run.step}.json')\n",
705
+ " print(probes.report(pr)); m.train()\n",
706
+ " return rep\n",
707
+ "\n",
708
+ "# 0.8.1 driver contract + the v3 halt: train(stop_at_boundary=True) RETURNS at every\n",
709
+ "# phase boundary (run._last_boundary), on a manual stop (run._interrupted — NEVER\n",
710
+ "# auto-resumed) and on a certified guard halt (run._guard_halt — NEVER auto-resumed).\n",
711
+ "t_end = time.time() + MAX_HOURS * 3600\n",
712
+ "while time.time() < t_end:\n",
713
+ " hours_left = (t_end - time.time()) / 3600\n",
714
+ " if hours_left < (0.2 if not LOCAL else 0.0):\n",
715
+ " break\n",
716
+ " # the boundary gates the design names: a stage-arm boundary needs the lawful geometry certified; the\n",
717
+ " # anneal boundary needs the multiplier from the screen — both are tests on the queue, checked here\n",
718
+ " nxt = run.manifest.current_phase()\n",
719
+ " if nxt is not None and not LOCAL:\n",
720
+ " if any(a.phase == nxt['name'] for a in (ARM_PROGRAM.cfg.arms if ARM_PROGRAM else [])) and not ARM_SPEC_CERTIFIED:\n",
721
+ " print(f\"BOUNDARY GATE: '{nxt['name']}' attaches a stage arm and the lawful geometry is not yet certified (2 seeds) — \"\n",
722
+ " \"the session stops here; the certification is on the card queue\"); break\n",
723
+ " if nxt['name'].startswith('anneal') and not isinstance(ANNEAL_LR_SCALE, (int, float)):\n",
724
+ " print(f\"BOUNDARY GATE: '{nxt['name']}' needs the anneal multiplier from the screen — the session stops here\"); break\n",
725
+ " run.train(max_hours=hours_left, stop_at_boundary=True, resume_after_halt=RESUME_AFTER_HALT)\n",
726
+ " RESUME_AFTER_HALT = False # one clearance per session, never standing\n",
727
+ " if getattr(run, '_interrupted', False):\n",
728
+ " print('manual stop - no auto-resume; resume state is on the hub'); break\n",
729
+ " halt = getattr(run, '_guard_halt', None)\n",
730
+ " if halt:\n",
731
+ " boundary_report(run, f\"guard_{halt['guard']}\")\n",
732
+ " print(f\"GUARD HALT {halt['guard']} at step {halt['step']:,} in '{halt['phase']}' — archive {halt['archive']}; \"\n",
733
+ " \"the session ends here; the driver (a human) decides: read the archive and the report, then a new session \"\n",
734
+ " \"with RESUME_AFTER_HALT=True continues from the last healthy checkpoint (a rewind target = the last boundary archive)\")\n",
735
+ " break\n",
736
+ " tag = getattr(run, '_last_boundary', None) or 'session_cap'\n",
737
+ " boundary_report(run, tag)\n",
738
+ " if run.manifest.current_phase() is None:\n",
739
+ " print('curriculum complete — the two-phase anneal was planned from birth and has run'); break\n",
740
+ " gc.collect(); torch.cuda.empty_cache() if DEVICE == 'cuda' else None\n",
741
+ "print('session over — resume state on the hub' if HF_TOKEN else 'session over — resume state local')\n"
742
+ ]
743
+ },
744
+ {
745
+ "cell_type": "code",
746
+ "execution_count": null,
747
+ "metadata": {},
748
+ "outputs": [],
749
+ "source": [
750
+ "# C5 — SAMPLES WITH VISIBLE SPECIALS. Run any time after prepare() (Cell T\n",
751
+ "# section); uses the in-memory model. Specials render as ⟦NAME⟧ — the eyeball\n",
752
+ "# check that the craft emits DOC at document ends (and, come anneal, END at\n",
753
+ "# turn closes). decode_visible is display-only and spoofable by content;\n",
754
+ "# the ids are the truth — never parse this string.\n",
755
+ "import torch\n",
756
+ "from geolip.alephllm.data.special_tokens import (DOC, decode_visible,\n",
757
+ " render_chat_ids)\n",
758
+ "\n",
759
+ "prompt = \"The history of astronomy begins with\"\n",
760
+ "ids = torch.tensor(run.tokenizer.encode(prompt), device=run.device)[None]\n",
761
+ "run.raw_model.eval()\n",
762
+ "with torch.no_grad():\n",
763
+ " out = run.raw_model.generate(ids, max_new=256, temperature=0.8)\n",
764
+ "print(decode_visible(out[0].tolist()))\n",
765
+ "\n",
766
+ "# chat-frame probe (meaningful once anneal has run; before that the frame\n",
767
+ "# is out-of-distribution and the continuation shows exactly that):\n",
768
+ "chat = render_chat_ids([{\"role\": \"user\", \"content\": \"Who are you?\"}])\n",
769
+ "import numpy as np\n",
770
+ "from geolip.alephllm.data.special_tokens import MODEL as MODEL_ID\n",
771
+ "seed = np.concatenate([chat, np.array([MODEL_ID])])\n",
772
+ "ids = torch.tensor(seed, device=run.device)[None]\n",
773
+ "with torch.no_grad():\n",
774
+ " out = run.raw_model.generate(ids, max_new=128, temperature=0.8)\n",
775
+ "print(\"\\n--- chat probe ---\")\n",
776
+ "print(decode_visible(out[0].tolist()))"
777
+ ]
778
+ },
779
+ {
780
+ "cell_type": "code",
781
+ "execution_count": null,
782
+ "metadata": {},
783
+ "outputs": [],
784
+ "source": [
785
+ "# C6 — THE ANNEAL WATCH. The two-phase anneal (nochat then chat) is PLANNED FROM BIRTH in\n",
786
+ "# the v3 preset (no activation step); this cell shows the multiplier in force and the\n",
787
+ "# per-checkpoint gauge table across the anneal reports (G6 = the termination read).\n",
788
+ "import json, glob, os\n",
789
+ "print('anneal LR multiplier:', run._phase_mult('anneal_nochat'), '/', run._phase_mult('anneal_mix'),\n",
790
+ " '(1.0 = the flat form; the value is the lead\\'s — recipe term H, 0 seeds)')\n",
791
+ "reps = sorted(glob.glob(os.path.join(REPORT_DIR, 'anneal*_step*.json')))\n",
792
+ "print(f\"{'report':<28}{'step':>8}{'val bpb':>9}{'doc bpb':>9}{'reset bpb':>10}{'head':>8}\")\n",
793
+ "for f in reps:\n",
794
+ " r = json.load(open(f, encoding='utf-8')); led = r.get('ledger') or {}; sp = r.get('special') or {}\n",
795
+ " v = led.get('bpb_full'); d = sp.get('doc_bpb'); rs = sp.get('reset_bpb'); h = led.get('toggle_head_aleph_off')\n",
796
+ " print(f\"{os.path.basename(f)[:27]:<28}{r['step']:>8}{(f'{v:.3f}' if isinstance(v, float) else '--'):>9}\"\n",
797
+ " f\"{(f'{d:.2f}' if isinstance(d, float) else '--'):>9}{(f'{rs:.2f}' if isinstance(rs, float) else '--'):>10}\"\n",
798
+ " f\"{(f'{h:+.3f}' if isinstance(h, float) else '--'):>8}\")\n",
799
+ "if run.guard is not None and run.guard.boundary_reads.get('G6'):\n",
800
+ " print('G6 termination reads:', run.guard.boundary_reads['G6'])\n"
801
+ ]
802
+ },
803
+ {
804
+ "cell_type": "code",
805
+ "execution_count": null,
806
+ "metadata": {},
807
+ "outputs": [],
808
+ "source": [
809
+ "# C4 — GROWTH TABLE from the boundary reports (reports/v3). Probe values are DICTS\n",
810
+ "# ({'acc': ...}); op reports carry no 'probes' — skipped, not crashed. Guard and arm\n",
811
+ "# columns added for v3.\n",
812
+ "import json, glob, os\n",
813
+ "from huggingface_hub import HfApi, hf_hub_download\n",
814
+ "from geolip.alephllm.presets import TRAINING_REPO\n",
815
+ "if LOCAL or not HF_TOKEN:\n",
816
+ " files = sorted(glob.glob(os.path.join(REPORT_DIR, '*.json')))\n",
817
+ " load = lambda f: json.load(open(f, encoding='utf-8'))\n",
818
+ "else:\n",
819
+ " api = HfApi(token=HF_TOKEN)\n",
820
+ " files = sorted(f for f in api.list_repo_files(TRAINING_REPO) if f.startswith(f'{CRAFT}/reports/v3/') and f.endswith('.json'))\n",
821
+ " load = lambda f: json.load(open(hf_hub_download(TRAINING_REPO, f, token=HF_TOKEN), encoding='utf-8'))\n",
822
+ "rows = []\n",
823
+ "for f in files:\n",
824
+ " r = load(f)\n",
825
+ " pr = r.get('probes')\n",
826
+ " if not pr:\n",
827
+ " continue\n",
828
+ " accs = {k.split('_', 1)[0]: round(v.get('acc', v) if isinstance(v, dict) else v, 2) for k, v in pr.items()}\n",
829
+ " led = r.get('ledger') or {}; sp = r.get('special') or {}\n",
830
+ " g = r.get('guard') or {}; fired = ','.join(sorted((g.get('fired') or {}).keys())) or '-'\n",
831
+ " arms = r.get('arms') or {}\n",
832
+ " arm_col = ' '.join(f\"{n}:{v.get('fineweb_delta'):+.3f}\" for n, v in arms.items() if isinstance(v, dict) and 'fineweb_delta' in v) or '-'\n",
833
+ " rows.append((r['tag'][:14], r['step'], round(r['tokens'] / 1e9, 3), led.get('bpb_full'), led.get('toggle_head_aleph_off'),\n",
834
+ " sp.get('doc_bpb'), fired, arm_col, accs))\n",
835
+ "rows.sort(key=lambda x: x[1])\n",
836
+ "print(f\"{'stage':<15}{'step':>7}{'tok(B)':>8}{'val':>7}{'head':>8}{'doc':>6} {'guards':<8}{'arms (fineweb delta)':<28}probes\")\n",
837
+ "for tag, step, tk, val, hd, doc, fired, arm_col, accs in rows:\n",
838
+ " v = f'{val:.3f}' if isinstance(val, float) else ' --'\n",
839
+ " h = f'{hd:+.3f}' if isinstance(hd, float) else ' --'\n",
840
+ " d = f'{doc:.1f}' if isinstance(doc, float) else ' --'\n",
841
+ " print(f'{tag:<15}{step:>7}{tk:>8}{v:>7}{h:>8}{d:>6} {fired:<8}{arm_col:<28}{accs}')\n"
842
+ ]
843
+ },
844
+ {
845
+ "cell_type": "code",
846
+ "execution_count": null,
847
+ "metadata": {},
848
+ "outputs": [],
849
+ "source": [
850
+ "# CARD-ONLY\n",
851
+ "# C7 — HEAD SCREEN: the instrument for the HEAD_BIRTH decision (S-1004 born-with-function).\n",
852
+ "# Optional, not part of the routine; runs on a free card at the chosen depth:\n",
853
+ "# can a live-from-birth head earn contribution in ~1k steps, or does even a\n",
854
+ "# live head lose to the untrained linear base? Verdict: init-law fix vs v3\n",
855
+ "# architectural modification. 4 arms x N_STEPS on fresh throwaway crafts;\n",
856
+ "# arm B/C installs at step 0 = BOUNDARY-WRITE at birth (provenance logged).\n",
857
+ "import gc, io, json, math, time, torch\n",
858
+ "import torch.nn.functional as F\n",
859
+ "from huggingface_hub import HfApi, hf_hub_download\n",
860
+ "from safetensors.torch import load_file\n",
861
+ "from geolip.alephllm import get_preset\n",
862
+ "from geolip.alephllm.model.alephlm import AlephLM\n",
863
+ "from geolip.alephllm.data.tokenizers import ByteTrigramTokenizer\n",
864
+ "from geolip.alephllm.data.streams import build_stream\n",
865
+ "from geolip.alephllm.train.optim import build_optimizers, apply_lr\n",
866
+ "from geolip.alephllm.train.revival import revive_head\n",
867
+ "from geolip.alephllm.train.instruments import head_liveness\n",
868
+ "\n",
869
+ "N_STEPS, GAUGE_EVERY, SEED = 1200, 300, 1337\n",
870
+ "ARMS = [\"A_born_null\", \"B_revival_birth\", \"C_matured_transplant\",\n",
871
+ " \"D_live_address_only\"]\n",
872
+ "MATURED = \"mini-beatrix-2s/checkpoints/step_00061422.safetensors\" # the 2s MISSION FINAL 16.1B - the matured head (d1024, transplantable)\n",
873
+ "pcfg = PRESETS[CRAFT]\n",
874
+ "tok = ByteTrigramTokenizer()\n",
875
+ "api = HfApi(token=HF_TOKEN)\n",
876
+ "vs = build_stream(\"wikitext-103\", tok, pcfg.model.context, 4,\n",
877
+ " seed=SEED + 9999, role=\"val\")\n",
878
+ "VAL = [vs.next_batch().cuda() for _ in range(2)]\n",
879
+ "\n",
880
+ "def head_toggle(model):\n",
881
+ " tot = {True: 0.0, False: 0.0}\n",
882
+ " with torch.no_grad(), torch.autocast(\"cuda\", dtype=torch.bfloat16):\n",
883
+ " for xb in VAL:\n",
884
+ " for off in (True, False):\n",
885
+ " out = model(xb[:, :-1], targets=xb[:, 1:],\n",
886
+ " disable_head_aleph=off)\n",
887
+ " tot[off] += float(out.loss) / len(VAL)\n",
888
+ " return (tot[True] - tot[False]) / math.log(2)\n",
889
+ "\n",
890
+ "def collect_birth(model):\n",
891
+ " hs, bl, ys = [], [], []\n",
892
+ " hook = model.nf.register_forward_hook(\n",
893
+ " lambda m, i, o: hs.append(o.detach().float().reshape(-1, o.shape[-1])))\n",
894
+ " with torch.no_grad(), torch.autocast(\"cuda\", dtype=torch.bfloat16):\n",
895
+ " for xb in VAL:\n",
896
+ " out = model(xb[:, :-1], disable_head_aleph=True)\n",
897
+ " bl.append(out.logits.float().reshape(-1, 256))\n",
898
+ " ys.append(xb[:, 1:].reshape(-1))\n",
899
+ " hook.remove()\n",
900
+ " return torch.cat(hs), torch.cat(bl), torch.cat(ys)\n",
901
+ "\n",
902
+ "for arm in ARMS:\n",
903
+ " torch.manual_seed(SEED)\n",
904
+ " m = AlephLM(pcfg.model).cuda()\n",
905
+ " prov = {\"arm\": arm, \"steps\": N_STEPS, \"seed\": SEED, \"gauges\": []}\n",
906
+ " if arm in (\"B_revival_birth\", \"D_live_address_only\"):\n",
907
+ " m = m.float()\n",
908
+ " H, B, Y = collect_birth(m)\n",
909
+ " prov[\"revival\"] = revive_head(m, H, B, Y, theta_deg=45.0)\n",
910
+ " if arm == \"D_live_address_only\":\n",
911
+ " m.head.w_s.weight.data.zero_()\n",
912
+ " if arm == \"C_matured_transplant\":\n",
913
+ " sd = load_file(hf_hub_download(\n",
914
+ " \"AbstractPhil/alephllm-mini-beatrix-training\", MATURED))\n",
915
+ " for k in (\"head.proj.weight\", \"head.addr.codebook\", \"head.w_s.weight\"):\n",
916
+ " m.state_dict()[k].copy_(sd[k])\n",
917
+ " if arm != \"A_born_null\": # frozen address per doctrine\n",
918
+ " m.head.proj.weight.requires_grad_(False)\n",
919
+ " m.head.addr.codebook.requires_grad_(False)\n",
920
+ " m = m.cuda().to(torch.float32)\n",
921
+ " opts = build_optimizers(m, pcfg.train.muon_lr, pcfg.train.muon_momentum,\n",
922
+ " pcfg.train.adam_lr)\n",
923
+ " st = build_stream(\"wikitext-103\", tok, pcfg.model.context, 8, seed=SEED)\n",
924
+ " m.train()\n",
925
+ " for step in range(1, N_STEPS + 1):\n",
926
+ " apply_lr(opts, [pcfg.train.muon_lr, pcfg.train.adam_lr], step, 200)\n",
927
+ " for o in opts:\n",
928
+ " o.zero_grad(set_to_none=True)\n",
929
+ " xb = st.next_batch().cuda()\n",
930
+ " with torch.autocast(\"cuda\", dtype=torch.bfloat16):\n",
931
+ " out = m(xb[:, :-1], targets=xb[:, 1:])\n",
932
+ " out.loss.backward()\n",
933
+ " torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)\n",
934
+ " for o in opts:\n",
935
+ " o.step()\n",
936
+ " if step % GAUGE_EVERY == 0 or step == N_STEPS:\n",
937
+ " m.eval()\n",
938
+ " g = dict(step=step,\n",
939
+ " toggle=head_toggle(m),\n",
940
+ " w_s_norm=float(m.head.w_s.weight.norm()),\n",
941
+ " **head_liveness(m, sample_idx=VAL[0][:2, :-1]))\n",
942
+ " prov[\"gauges\"].append(g)\n",
943
+ " print(f\"{arm} step {step}: toggle {g['toggle']:+.4f} \"\n",
944
+ " f\"live {g['head_liveness_ratio']:.3f}x \"\n",
945
+ " f\"||W_s|| {g['w_s_norm']:.1f}\")\n",
946
+ " m.train()\n",
947
+ " api.upload_file(\n",
948
+ " path_or_fileobj=json.dumps(prov, default=float).encode(),\n",
949
+ " path_in_repo=f\"{CRAFT}/reports/v3/cultivation_{arm}.json\",\n",
950
+ " repo_id=\"AbstractPhil/alephllm-mini-beatrix-training\",\n",
951
+ " commit_message=f\"head cultivation screen: {arm}\")\n",
952
+ " del m, opts, st\n",
953
+ " gc.collect(); torch.cuda.empty_cache()\n",
954
+ "print(\"SCREEN COMPLETE - 4 reports under reports/v3/cultivation_*.json\")"
955
+ ]
956
+ },
957
+ {
958
+ "cell_type": "markdown",
959
+ "metadata": {},
960
+ "source": [
961
+ "### Post-training programs (placeholders — the lead's; nothing below is invented)\n",
962
+ "- **S13 thinking**: trained post-training; think markers are a specials-plane decision (the `THINK` special is reserved in the registry); the honesty gauge is mandatory. `THINK = None`.\n",
963
+ "- **S6 diversity / condensing terms** (recipe term L): `DIVERSITY = CONDENSING = None`.\n",
964
+ "- **S7 tool-packaged arms** (recipe term M): `TOOL_ARMS = None`.\n",
965
+ "- **C3 Level-2 arms (memory accumulators, RelayEMA)**: admitted only after data-route saturation (S11); the head form is packaged (0.8.8 `model/relay.py`), untested under demand (L8 owed).\n",
966
+ "- **C5 growth clause (A6)**: routed attention from arms adjusted as the model grows — his terms, open.\n",
967
+ "- **Born-in core-side objectives (D4)**: door CLOSED by L3 (the sub3 wall holds core-side at a catastrophic price, S-1905) — v3 is a steering-and-arms craft.\n",
968
+ "- **Hub K-alpha gain (A3/A4/S5)**: an inference-parity-certified instrument in the docket, not in the library; training under it is gated on the lead's bed word. `HUB_GAIN = None`.\n",
969
+ "\n",
970
+ "### Notes\n",
971
+ "- **Controls**: `<craft>-control` (pure sdpa) is registered beside the craft by C2; any v3 claim runs its twin under the same data plane.\n",
972
+ "- **Monitoring keys**: `governor/hits_cum` (TB), `guard/<G>` (the step a guard fired), `arms/abstention`, `train/lr_scale` (carries the anneal multiplier); `hub_addr.anchor_merge_pairs` must stay 0.\n",
973
+ "- **Halts**: a certified guard's archive is `resume/guard_<G>_step<N>.pt`; `resume/latest.pt` is the last healthy checkpoint; the manifest's `halt` field blocks `train()` until a session clears it.\n",
974
+ "- **Kernels**: eager on Blackwell; `hub_chunk=256`; fp16 forbidden. Sessions are boundary-exact.\n"
975
+ ]
976
+ },
977
+ {
978
+ "cell_type": "code",
979
+ "execution_count": null,
980
+ "metadata": {},
981
+ "outputs": [],
982
+ "source": [
983
+ "# POST-TRAINING — refuses until a program of record is supplied (see the notes above).\n",
984
+ "for name in ('THINK', 'DIVERSITY', 'CONDENSING', 'TOOL_ARMS'):\n",
985
+ " if globals().get(name) is None:\n",
986
+ " print(f'{name}: no program supplied — the lead\\'s (plan S13 / S6 / S7); nothing runs')\n",
987
+ " else:\n",
988
+ " raise SystemExit(f'{name} is set but no post-training routine is built in 0.8.9 — the program is a design item, not a switch')\n"
989
+ ]
990
+ }
991
+ ],
992
+ "metadata": {
993
+ "accelerator": "GPU",
994
+ "colab": {
995
+ "provenance": []
996
+ },
997
+ "kernelspec": {
998
+ "display_name": "Python 3",
999
+ "name": "python3"
1000
+ },
1001
+ "language_info": {
1002
+ "name": "python"
1003
+ }
1004
+ },
1005
+ "nbformat": 4,
1006
+ "nbformat_minor": 0
1007
+ }