zsqzz commited on
Commit
2244b1e
·
verified ·
1 Parent(s): 3cb10b3

Archive experiment updates 2026-10-08 (27/119)

Browse files

File-level snapshot; code revision eb6fa2872daec8b3cea3832ee9dfec9e63cf2176. Weights and Docker images remain local.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_transfer.py +653 -0
  2. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_readout_control.py +373 -0
  3. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_relation_response.py +187 -0
  4. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py +372 -0
  5. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py +192 -0
  6. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py +242 -0
  7. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py +446 -0
  8. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py +446 -0
  9. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py +327 -0
  10. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_train.py +353 -0
  11. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_reencoding.py +438 -0
  12. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_workspace.py +1112 -0
  13. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_controls.py +64 -0
  14. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_scaling.py +193 -0
  15. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/cli.py +32 -0
  16. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/composition_curves.py +477 -0
  17. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/curve_tracking.py +36 -0
  18. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step.py +669 -0
  19. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py +371 -0
  20. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py +589 -0
  21. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiment_tracking.py +298 -0
  22. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiments.py +39 -0
  23. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth.py +431 -0
  24. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py +631 -0
  25. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_data.py +281 -0
  26. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_extension.py +73 -0
  27. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_data.py +346 -0
  28. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py +549 -0
  29. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_model.py +108 -0
  30. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py +342 -0
  31. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py +353 -0
  32. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py +349 -0
  33. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_train.py +214 -0
  34. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop.py +278 -0
  35. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop_data.py +245 -0
  36. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_data.py +397 -0
  37. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_train.py +261 -0
  38. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py +421 -0
  39. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_reproduction.py +563 -0
  40. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_data.py +396 -0
  41. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_followup.py +103 -0
  42. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_future.py +148 -0
  43. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_interface.py +566 -0
  44. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_learning.py +187 -0
  45. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_model.py +339 -0
  46. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_statistics.py +168 -0
  47. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_train.py +811 -0
  48. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/independent_alignment.py +124 -0
  49. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_editing.py +759 -0
  50. docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_tracking.py +203 -0
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_transfer.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prospective v2.13: forward-preserving path interventions and local transfer.
2
+
3
+ Only a single MLP output weight is differentiated/updated in production.
4
+ Downstream parameters are frozen; the custom attention paths alter its input VJP.
5
+ """
6
+
7
+ import argparse
8
+ import fcntl
9
+ import hashlib
10
+ import itertools
11
+ import json
12
+ import os
13
+ import platform
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from contextlib import contextmanager
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from types import MethodType
21
+
22
+ import numpy as np
23
+ import torch
24
+ from torch.nn import functional as F
25
+
26
+ from .bios_cross import edit_pair, make_cross_world
27
+ from .bios_cross_train import tensor_queries
28
+ from .bios_data import EOS, array_hash, write_json
29
+ from .bios_model import CausalLM, ModelConfig
30
+
31
+ ROOT = Path(__file__).resolve().parents[2]
32
+ CONFIG = ROOT / "configs/bios-path-transfer-v1.json"
33
+ ARMS = ("full", "no_cross", "no_mlp", "fixed_qk")
34
+
35
+
36
+ def stamp():
37
+ return datetime.now(timezone.utc).isoformat()
38
+
39
+
40
+ def sha(path):
41
+ result = hashlib.sha256()
42
+ with Path(path).open("rb") as stream:
43
+ for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
44
+ result.update(chunk)
45
+ return result.hexdigest()
46
+
47
+
48
+ def tensor_sha(value):
49
+ return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
50
+
51
+
52
+ def inner(a, b):
53
+ return (a.double() * b.double()).sum().item()
54
+
55
+
56
+ def norm(a):
57
+ return a.double().norm().item()
58
+
59
+
60
+ def relative(a, b):
61
+ return norm(a - b) / max(norm(b), 1e-30)
62
+
63
+
64
+ def cosine(a, b):
65
+ return inner(a, b) / max(norm(a) * norm(b), 1e-30)
66
+
67
+
68
+ def attention_surrogate(module, x, mode):
69
+ """Correct input Jacobian for frozen QK, or only the diagonal position blocks.
70
+
71
+ no_cross makes T copies of the input: copy s only differentiates x_s,
72
+ then computes output s with the full original causal context. Thus Q_s,
73
+ K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish.
74
+ """
75
+ batch, length, width = x.shape
76
+ heads, dim = module.heads, width // module.heads
77
+ if mode == "no_cross":
78
+ expanded = x[:, None].expand(batch, length, length, width)
79
+ diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None]
80
+ routed = expanded.detach() + diagonal * (expanded - expanded.detach())
81
+ q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3)
82
+ index = torch.arange(length, device=x.device)
83
+ q = q[:, index, index] # B, query, H, D
84
+ scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5
85
+ mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril()
86
+ a = scores.masked_fill(~mask, -torch.inf).softmax(-1)
87
+ output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width)
88
+ else:
89
+ q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2)
90
+ scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5
91
+ mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril()
92
+ a = scores.masked_fill(~mask, -torch.inf).softmax(-1)
93
+ if mode == "fixed_qk":
94
+ a = a.detach()
95
+ elif mode != "manual_full":
96
+ raise ValueError(mode)
97
+ output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width)
98
+ return module.proj(output)
99
+
100
+
101
+ @contextmanager
102
+ def path_mode(model, layer, arm):
103
+ if arm not in (*ARMS, "manual_full"):
104
+ raise ValueError(arm)
105
+ saved = []
106
+ try:
107
+ for block in model.blocks[layer + 1 :]:
108
+ if arm == "no_mlp":
109
+ module = block.mlp
110
+ original = module.forward
111
+
112
+ def stopped(self, x, original=original):
113
+ with torch.no_grad():
114
+ return original(x)
115
+
116
+ module.forward = MethodType(stopped, module)
117
+ saved.append((module, original))
118
+ elif arm != "full":
119
+ module = block.attention
120
+ original = module.forward
121
+
122
+ def altered(self, x, original=original, arm=arm):
123
+ with torch.no_grad():
124
+ reference = original(x)
125
+ surrogate = attention_surrogate(self, x, arm)
126
+ return reference + (surrogate - surrogate.detach())
127
+
128
+ module.forward = MethodType(altered, module)
129
+ saved.append((module, original))
130
+ yield
131
+ finally:
132
+ for module, original in saved:
133
+ module.forward = original
134
+
135
+
136
+ def cases(world):
137
+ result = []
138
+ for chain in range(2):
139
+ pair = edit_pair(world, chain)
140
+ for group in pair["groups"]:
141
+ members = np.flatnonzero(world.memberships[chain] == group)
142
+ eligible = members[
143
+ np.isin(world.derived_ids[chain, members], world.heldout_ids)
144
+ & np.isin(world.derived_ids[chain, members], pair["conflict_D"])
145
+ ]
146
+ if not len(eligible):
147
+ raise ValueError("No prespecified heldout conflict person")
148
+ person = int(eligible[0])
149
+ others = members[
150
+ (members != person)
151
+ & ~world.exceptions[chain, members]
152
+ & np.isin(world.derived_ids[chain, members], world.heldout_ids)
153
+ ]
154
+ if not len(others):
155
+ raise ValueError("No prespecified second heldout person")
156
+ other = int(others[0])
157
+ distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0])
158
+ root = int(world.root_ids[chain, group])
159
+ actual = int(world.actual_ids[chain, person])
160
+ default = int(pair["coherent"][root])
161
+ alternative = int(pair["exception"][actual])
162
+ if default == alternative:
163
+ raise ValueError("Selected person is not a new conflict")
164
+ for kind in ("root", "coherent", "conflict"):
165
+ source = root if kind == "root" else actual
166
+ target = alternative if kind == "conflict" else default
167
+ associated = actual if kind == "root" else root
168
+ ids = [
169
+ source,
170
+ int(world.derived_ids[chain, person]),
171
+ int(world.derived_ids[chain, other]),
172
+ associated,
173
+ int(world.actual_ids[1 - chain, person]),
174
+ int(world.actual_ids[chain, distant]),
175
+ ]
176
+ targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()]
177
+ result.append(
178
+ {
179
+ "name": f"chain-{chain}-group-{int(group)}-{kind}",
180
+ "chain": chain,
181
+ "group": int(group),
182
+ "kind": kind,
183
+ "person": person,
184
+ "other_person": other,
185
+ "ids": ids,
186
+ "targets": targets,
187
+ "old_targets": world.answers[ids].tolist(),
188
+ "roles": [
189
+ "source",
190
+ "derived_same",
191
+ "derived_other",
192
+ "associated",
193
+ "retention_local",
194
+ "retention_distant",
195
+ ],
196
+ }
197
+ )
198
+ return result
199
+
200
+
201
+ def example_data(world, case, device):
202
+ # Use the original interface, including teacher-forced answer for EOS loss.
203
+ targets = world.answers.copy()
204
+ targets[case["ids"]] = case["targets"]
205
+ all_data = tensor_queries(world, device, targets)
206
+ ids = torch.tensor(case["ids"], device=device)
207
+ return {key: value[ids] for key, value in all_data.items()}
208
+
209
+
210
+ def subset(data, ids):
211
+ return {key: value[ids] for key, value in data.items()}
212
+
213
+
214
+ def losses(logits, labels):
215
+ return (
216
+ F.cross_entropy(
217
+ logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none"
218
+ )
219
+ .reshape(-1, 2)
220
+ .mean(-1)
221
+ )
222
+
223
+
224
+ def measure(model, data, layer, arm):
225
+ projection = model.blocks[layer].mlp.down
226
+ captured = {}
227
+
228
+ def hook(module, inputs, output):
229
+ captured["z"], captured["h"] = inputs[0], output
230
+
231
+ handle = projection.register_forward_hook(hook)
232
+ try:
233
+ with path_mode(model, layer, arm):
234
+ logits = model(data["tokens"], data["positions"])
235
+ loss = losses(logits, data["labels"])
236
+ actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"]))
237
+ z = captured["z"].detach()
238
+ delta = delta.detach()
239
+ per_position = torch.einsum("btd,btk->btdk", delta, z)
240
+ mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool)
241
+ mask.scatter_(1, data["positions"], True)
242
+ g = per_position.sum(1)
243
+ supervised = (per_position * mask[:, :, None, None]).sum(1)
244
+ unsupervised = (per_position * ~mask[:, :, None, None]).sum(1)
245
+ return {
246
+ "z": z,
247
+ "delta": delta,
248
+ "g": g,
249
+ "supervised": supervised,
250
+ "unsupervised": unsupervised,
251
+ "mask": mask,
252
+ "loss": loss.detach(),
253
+ "logits": logits.detach(),
254
+ "reconstruction_error": relative(g.sum(0), actual),
255
+ "decomposition_error": relative(supervised + unsupervised, g),
256
+ }
257
+ finally:
258
+ handle.remove()
259
+
260
+
261
+ @torch.no_grad()
262
+ def assess(model, data):
263
+ logits = model(data["tokens"], data["positions"])
264
+ loss = losses(logits, data["labels"])
265
+ first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1)
266
+ continuation = data["tokens"].clone()
267
+ rows = torch.arange(len(first), device=first.device)
268
+ continuation[rows, data["lengths"]] = first
269
+ ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS)
270
+ return loss, first, ended
271
+
272
+
273
+ def frozen_files(config):
274
+ paths = [
275
+ CONFIG,
276
+ Path(__file__),
277
+ ROOT / "scripts/run_bios_path_transfer.py",
278
+ ROOT / "tests/test_bios_path_transfer.py",
279
+ ]
280
+ for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"):
281
+ paths.append(ROOT / "src/llm_memory_editability" / name)
282
+ for world in config["worlds"]:
283
+ directory = ROOT / config["source_world_root"] / f"world-{world}"
284
+ paths += [
285
+ directory / "world.npz",
286
+ directory / "metadata.json",
287
+ directory / "evaluation.npz",
288
+ ]
289
+ for world, seed in itertools.product(config["worlds"], config["seeds"]):
290
+ directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither"
291
+ paths += [directory / "config.json", directory / "learning-complete.json"]
292
+ paths += [directory / f"model-{step}.pt" for step in config["states"]]
293
+ return paths
294
+
295
+
296
+ def freeze(config):
297
+ directory = ROOT / config["artifacts"]
298
+ directory.mkdir(parents=True, exist_ok=True)
299
+ lock_path = directory / "preregistration-lock.json"
300
+ if lock_path.exists():
301
+ raise FileExistsError("Cannot replace a prospective lock")
302
+ protocol = (
303
+ "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1]
304
+ )
305
+ (directory / "preregistration.md").write_text(protocol)
306
+ manifests = {}
307
+ for world in config["worlds"]:
308
+ generated = make_cross_world(world, ROOT / config["source_world_root"])
309
+ selected = cases(generated)
310
+ if len(selected) != config["cases_per_state"]:
311
+ raise ValueError("Case count mismatch")
312
+ manifests[str(world)] = {
313
+ "truth_sha256": array_hash(generated.answers),
314
+ "prompts_sha256": array_hash(generated.prompts),
315
+ "cases": selected,
316
+ }
317
+ write_json(directory / "cases.json", manifests)
318
+ sources = {}
319
+ for path in frozen_files(config):
320
+ relative_path = path.relative_to(ROOT)
321
+ sources[str(relative_path)] = sha(path)
322
+ if relative_path.parts[0] in ("src", "scripts", "tests", "configs"):
323
+ destination = directory / "frozen-files" / relative_path
324
+ destination.parent.mkdir(parents=True, exist_ok=True)
325
+ destination.write_bytes(path.read_bytes())
326
+ lock = {
327
+ "created_at": stamp(),
328
+ "config": config,
329
+ "sources": sources,
330
+ "protocol_sha256": sha(directory / "preregistration.md"),
331
+ "cases_sha256": sha(directory / "cases.json"),
332
+ "torch": torch.__version__,
333
+ "numpy": np.__version__,
334
+ "python": platform.python_version(),
335
+ }
336
+ write_json(lock_path, lock)
337
+ return {"path": str(lock_path), "sha256": sha(lock_path)}
338
+
339
+
340
+ def verify_lock(config):
341
+ directory = ROOT / config["artifacts"]
342
+ path = directory / "preregistration-lock.json"
343
+ lock = json.loads(path.read_text())
344
+ if lock["config"] != config or lock["torch"] != torch.__version__:
345
+ raise ValueError("Frozen config/runtime mismatch")
346
+ for name, digest in lock["sources"].items():
347
+ if sha(ROOT / name) != digest:
348
+ raise ValueError("Frozen input changed: " + name)
349
+ for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")):
350
+ if sha(directory / name) != lock[key]:
351
+ raise ValueError("Prospective manifest changed")
352
+ return sha(path)
353
+
354
+
355
+ def save_factors(path, baseline, sources, data):
356
+ arrays = {
357
+ "positions": data["positions"].cpu().numpy(),
358
+ "labels": data["labels"].cpu().numpy(),
359
+ "tokens": data["tokens"].cpu().numpy(),
360
+ }
361
+ for prefix, result in [("evaluation", baseline), *sources.items()]:
362
+ for key in ("z", "delta", "loss"):
363
+ arrays[prefix + "_" + key] = result[key].cpu().numpy()
364
+ np.savez_compressed(path, **arrays)
365
+
366
+
367
+ def run_case(model, world, case, config, destination):
368
+ layer = config["target_layer"]
369
+ w = model.blocks[layer].mlp.down.weight
370
+ parent = w.detach().clone()
371
+ frozen_before = {
372
+ name: tensor_sha(value)
373
+ for name, value in model.state_dict().items()
374
+ if name != config["target_parameter"]
375
+ }
376
+ data = example_data(world, case, w.device)
377
+ baseline = measure(model, data, layer, "full")
378
+ before, old_prediction, old_ended = assess(model, data)
379
+ sources, diagnostics, updates = {}, [], []
380
+ with torch.no_grad():
381
+ if not torch.equal(before, baseline["loss"]):
382
+ raise ValueError("Evaluation/gradient forward mismatch")
383
+ for arm in config["arms"]:
384
+ source = measure(model, subset(data, slice(0, 1)), layer, arm)
385
+ sources[arm] = source
386
+ error = (source["logits"] - sources["full"]["logits"]).abs().max().item()
387
+ if error > config["forward_tolerance"]:
388
+ raise ValueError(f"Forward preservation failed: {error}")
389
+ if (
390
+ max(source["reconstruction_error"], baseline["reconstruction_error"])
391
+ > config["gradient_tolerance"]
392
+ ):
393
+ raise ValueError("Outer-product reconstruction failed")
394
+ direction = source["g"][0]
395
+ gfull = sources["full"]["g"][0]
396
+ if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9:
397
+ raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient")
398
+ for j, role in enumerate(case["roles"]):
399
+ row = {
400
+ "arm": arm,
401
+ "role": role,
402
+ "probe": j,
403
+ "forward_error": error,
404
+ "reconstruction_error": source["reconstruction_error"],
405
+ "gradient_norm": norm(direction),
406
+ "gradient_cosine_full": cosine(direction, gfull),
407
+ "supervised_norm": norm(source["supervised"]),
408
+ "unsupervised_norm": norm(source["unsupervised"]),
409
+ "kernel": inner(baseline["g"][j], direction),
410
+ "source_loss": source["loss"].item(),
411
+ "probe_loss": before[j].item(),
412
+ }
413
+ for left, right in itertools.product(("supervised", "unsupervised"), repeat=2):
414
+ row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0])
415
+ diagnostics.append(row)
416
+ for scale, fraction in itertools.product(config["scales"], config["step_fractions"]):
417
+ denominator = norm(gfull if scale == "shared_lr" else direction)
418
+ eta = fraction * norm(parent) / denominator if denominator else 0.0
419
+ with torch.no_grad():
420
+ w.copy_(parent - eta * direction)
421
+ displacement = w.detach() - parent
422
+ weight_hash = tensor_sha(w)
423
+ after, predicted_token, ended = assess(model, data)
424
+ predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2))
425
+ for j, role in enumerate(case["roles"]):
426
+ updates.append(
427
+ {
428
+ "arm": arm,
429
+ "scale": scale,
430
+ "fraction": fraction,
431
+ "eta": eta,
432
+ "update_norm": norm(displacement),
433
+ "weight_sha256": weight_hash,
434
+ "role": role,
435
+ "probe": j,
436
+ "id": case["ids"][j],
437
+ "target": case["targets"][j],
438
+ "old_target": case["old_targets"][j],
439
+ "before": before[j].item(),
440
+ "after": after[j].item(),
441
+ "observed_change": (after[j] - before[j]).item(),
442
+ "predicted_change": predicted[j].item(),
443
+ "ideal_predicted_change": -eta * inner(baseline["g"][j], direction),
444
+ "baseline_prediction": int(old_prediction[j]),
445
+ "baseline_ended": bool(old_ended[j]),
446
+ "prediction": int(predicted_token[j]),
447
+ "ended": bool(ended[j]),
448
+ }
449
+ )
450
+ with torch.no_grad():
451
+ w.copy_(parent)
452
+ if not torch.equal(w, parent):
453
+ raise ValueError("Parent weight was not restored")
454
+ frozen_after = {
455
+ name: tensor_sha(value)
456
+ for name, value in model.state_dict().items()
457
+ if name != config["target_parameter"]
458
+ }
459
+ if frozen_before != frozen_after:
460
+ raise ValueError("A frozen parameter changed")
461
+ destination.mkdir(parents=True, exist_ok=True)
462
+ save_factors(destination / "factors.npz", baseline, sources, data)
463
+ write_json(
464
+ destination / "measurements.json",
465
+ {"case": case, "diagnostics": diagnostics, "updates": updates},
466
+ )
467
+ write_json(
468
+ destination / "receipt.json",
469
+ {
470
+ "finished_at": stamp(),
471
+ "files": {
472
+ name: sha(destination / name) for name in ("factors.npz", "measurements.json")
473
+ },
474
+ "baseline_reconstruction_error": baseline["reconstruction_error"],
475
+ "frozen_parameters_unchanged": True,
476
+ "parent_restored": True,
477
+ },
478
+ )
479
+
480
+
481
+ def verify_receipt(directory):
482
+ receipt = json.loads((directory / "receipt.json").read_text())
483
+ for name, digest in receipt["files"].items():
484
+ if sha(directory / name) != digest:
485
+ raise ValueError("Receipt mismatch: " + str(directory / name))
486
+
487
+
488
+ def run(config, world_id, seed, device):
489
+ lock_hash = verify_lock(config)
490
+ if world_id not in config["worlds"] or seed not in config["seeds"]:
491
+ raise ValueError("Worker outside the frozen matrix")
492
+ torch.set_num_threads(2)
493
+ torch.backends.cuda.matmul.allow_tf32 = False
494
+ torch.backends.cudnn.allow_tf32 = False
495
+ world = make_cross_world(world_id, ROOT / config["source_world_root"])
496
+ name = f"world-{world_id}-seed-{seed}-neither"
497
+ source = ROOT / config["parent_root"] / name
498
+ out = ROOT / config["output"] / name
499
+ out.mkdir(parents=True, exist_ok=True)
500
+ with (out / ".lock").open("a") as stream:
501
+ fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
502
+ started = time.monotonic()
503
+ write_json(
504
+ out / "runtime.json",
505
+ {
506
+ "started_at": stamp(),
507
+ "lock_sha256": lock_hash,
508
+ "device": str(device),
509
+ "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None,
510
+ "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"),
511
+ "torch": torch.__version__,
512
+ },
513
+ )
514
+ for step in config["states"]:
515
+ checkpoint = torch.load(
516
+ source / f"model-{step}.pt", map_location="cpu", weights_only=False
517
+ )
518
+ if checkpoint["step"] != step:
519
+ raise ValueError("Parent step mismatch")
520
+ model = CausalLM(ModelConfig(**checkpoint["config"])).to(device)
521
+ model.load_state_dict(checkpoint["model"])
522
+ model.eval()
523
+ for pname, parameter in model.named_parameters():
524
+ parameter.requires_grad_(pname == config["target_parameter"])
525
+ selected = cases(world)
526
+ state_out = out / f"step-{step}"
527
+ state_out.mkdir(exist_ok=True)
528
+ # Original-forward repeated gradient, not a new scientific sample.
529
+ sham_data = subset(example_data(world, selected[0], device), slice(0, 1))
530
+ first = measure(model, sham_data, config["target_layer"], "full")
531
+ second = measure(model, sham_data, config["target_layer"], "full")
532
+ sham_error = relative(first["g"], second["g"])
533
+ if sham_error > config["gradient_tolerance"]:
534
+ raise ValueError("Sham gradient failed")
535
+ write_json(state_out / "sham.json", {"relative_gradient_error": sham_error})
536
+ for case in selected:
537
+ destination = state_out / case["name"]
538
+ if (destination / "receipt.json").exists():
539
+ verify_receipt(destination)
540
+ else:
541
+ run_case(model, world, case, config, destination)
542
+ print(
543
+ json.dumps(
544
+ {
545
+ "event": "case",
546
+ "world": world_id,
547
+ "seed": seed,
548
+ "step": step,
549
+ "case": case["name"],
550
+ }
551
+ ),
552
+ flush=True,
553
+ )
554
+ del model, checkpoint
555
+ files = {
556
+ str(path.relative_to(out)): sha(path)
557
+ for path in out.rglob("*")
558
+ if path.is_file() and path.name not in (".lock", "complete.json")
559
+ }
560
+ write_json(
561
+ out / "complete.json",
562
+ {
563
+ "finished_at": stamp(),
564
+ "seconds": time.monotonic() - started,
565
+ "lock_sha256": lock_hash,
566
+ "cases": len(config["states"]) * len(selected),
567
+ "files": files,
568
+ },
569
+ )
570
+
571
+
572
+ def dispatch(config, gpus):
573
+ verify_lock(config)
574
+ output = ROOT / config["output"]
575
+ output.mkdir(parents=True, exist_ok=True)
576
+ jobs = list(itertools.product(config["worlds"], config["seeds"]))
577
+ active, finished = [], []
578
+ with (output / ".dispatch.lock").open("a") as lock:
579
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
580
+ while jobs or active:
581
+ for gpu in gpus:
582
+ if jobs and not any(item["gpu"] == gpu for item in active):
583
+ world, seed = jobs.pop(0)
584
+ path = output / f"world-{world}-seed-{seed}-neither"
585
+ if (path / "complete.json").exists():
586
+ finished.append({"world": world, "seed": seed, "reused": True})
587
+ continue
588
+ log = (output / f"world-{world}-seed-{seed}.log").open("a")
589
+ env = {
590
+ **os.environ,
591
+ "CUDA_VISIBLE_DEVICES": str(gpu),
592
+ "PYTHONPATH": str(ROOT / "src"),
593
+ "OMP_NUM_THREADS": "2",
594
+ "OPENBLAS_NUM_THREADS": "2",
595
+ }
596
+ command = [
597
+ sys.executable,
598
+ str(ROOT / "scripts/run_bios_path_transfer.py"),
599
+ "worker",
600
+ "--world",
601
+ str(world),
602
+ "--seed",
603
+ str(seed),
604
+ "--device",
605
+ "cuda:0",
606
+ ]
607
+ proc = subprocess.Popen(
608
+ command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT
609
+ )
610
+ active.append(
611
+ {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log}
612
+ )
613
+ for item in active[:]:
614
+ code = item["process"].poll()
615
+ if code is not None:
616
+ item["log"].close()
617
+ record = {k: item[k] for k in ("gpu", "world", "seed")}
618
+ finished.append({**record, "returncode": code})
619
+ active.remove(item)
620
+ write_json(
621
+ output / "dispatch.json",
622
+ {
623
+ "updated_at": stamp(),
624
+ "pending": jobs,
625
+ "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active],
626
+ "finished": finished,
627
+ },
628
+ )
629
+ if active:
630
+ time.sleep(2)
631
+ if any(item.get("returncode", 0) for item in finished):
632
+ raise RuntimeError("One or more workers failed; inspect preserved logs")
633
+
634
+
635
+ def main():
636
+ parser = argparse.ArgumentParser()
637
+ parser.add_argument("command", choices=("freeze", "worker", "dispatch"))
638
+ parser.add_argument("--world", type=int)
639
+ parser.add_argument("--seed", type=int)
640
+ parser.add_argument("--device", default="cuda:0")
641
+ parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8])
642
+ args = parser.parse_args()
643
+ config = json.loads(CONFIG.read_text())
644
+ if args.command == "freeze":
645
+ print(json.dumps(freeze(config)))
646
+ elif args.command == "worker":
647
+ run(config, args.world, args.seed, torch.device(args.device))
648
+ else:
649
+ dispatch(config, args.gpus)
650
+
651
+
652
+ if __name__ == "__main__":
653
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_readout_control.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """H5: original E93 exception edits of all weights except tied token/readout weights."""
2
+
3
+ import argparse
4
+ import fcntl
5
+ import json
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world
13
+ from .bios_cross_continue import (
14
+ capture_state,
15
+ edit_metrics,
16
+ edit_update,
17
+ file_hash,
18
+ restore_state,
19
+ validate_optimizer,
20
+ )
21
+ from .bios_cross_train import evaluate, source_hashes, tensor_queries
22
+ from .bios_data import array_hash, rng_for, write_json
23
+ from .bios_model import CausalLM, ModelConfig
24
+ from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash
25
+ from .bios_train import precision
26
+
27
+ CHECKPOINTS = (0, 32, 128, 512)
28
+ SCOPE = "all-freeze-embedding"
29
+ STUDY = {
30
+ "protocol": "v2.8-h5-readout-control-E93",
31
+ "widths": [256, 768],
32
+ "parent_step": 15360,
33
+ "worlds": [0, 1],
34
+ "seeds": [0, 1],
35
+ "conditions": list(CONDITIONS),
36
+ "chains": list(CHAINS),
37
+ "kind": "exception",
38
+ "scope": SCOPE,
39
+ "frozen": "token.weight, shared by input embedding and output F.linear readout",
40
+ "trainable": "all other parameters, including absolute position embedding",
41
+ "lr": 3e-5,
42
+ "weight_decay": 0.1,
43
+ "edit_batch": 128,
44
+ "replay_batch": 128,
45
+ "retention_kl": 1.0,
46
+ "clip_norm": 1.0,
47
+ "steps": 512,
48
+ "checkpoints": list(CHECKPOINTS),
49
+ "resume_every": 32,
50
+ "models": 24,
51
+ "edit_cases": 48,
52
+ "E": 93,
53
+ "D": 96,
54
+ "R": 4096,
55
+ "reference_scopes": ["mlp", "all"],
56
+ "selection": "all fixed512 endpoints; no best step",
57
+ }
58
+
59
+
60
+ def validate_study(study):
61
+ if study != STUDY:
62
+ raise ValueError("H5 configuration differs from the fixed contract")
63
+
64
+
65
+ def control_sources():
66
+ return {
67
+ **source_hashes(),
68
+ "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")),
69
+ Path(__file__).name: file_hash(__file__),
70
+ }
71
+
72
+
73
+ def select_control_parameters(model):
74
+ """The ordinary model passes this same Parameter directly to F.linear."""
75
+ excluded = id(model.token.weight)
76
+ selected = []
77
+ for parameter in model.parameters():
78
+ parameter.requires_grad_(id(parameter) != excluded)
79
+ parameter.grad = None
80
+ if parameter.requires_grad:
81
+ selected.append(parameter)
82
+ assert model.position.weight.requires_grad and not model.token.weight.requires_grad
83
+ return selected
84
+
85
+
86
+ def sampling_stream(world_seed, chain, steps=512, batch=128):
87
+ rng = rng_for(world_seed, 908, chain)
88
+ return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch))
89
+
90
+
91
+ def score_arrays(arrays, truth):
92
+ for key in ("prediction", "ended", "correct"):
93
+ if arrays[key].shape != truth.shape:
94
+ raise ValueError("H5 prediction array shape mismatch")
95
+ if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_:
96
+ raise ValueError("H5 EOS/correct flags must be Boolean")
97
+ np.testing.assert_array_equal(
98
+ arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"]
99
+ )
100
+ return arrays
101
+
102
+
103
+ def validate_parent_config(config, world):
104
+ width = config["model"]["width"]
105
+ if width not in STUDY["widths"] or config["world"] not in (0, 1):
106
+ raise ValueError("H5 parent outside original size/world matrix")
107
+ expected = dict(
108
+ vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128
109
+ )
110
+ if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover":
111
+ raise ValueError("H5 needs original unrestricted low-prevalence architecture")
112
+ expected_study = dict(
113
+ steps=15360,
114
+ lr=1e-4,
115
+ documents_per_step=16,
116
+ facts_per_document=10,
117
+ QA_per_chain_per_step=20,
118
+ document_QA_weights=[0.8, 0.2],
119
+ )
120
+ if any(config["study"][key] != value for key, value in expected_study.items()):
121
+ raise ValueError("H5 parent is not the original learning budget")
122
+ if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS:
123
+ raise ValueError("H5 parent outside original initialization/organization matrix")
124
+ if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers):
125
+ raise ValueError("H5 parent source or truth mismatch")
126
+ if config["torch"] != torch.__version__ or config["numpy"] != np.__version__:
127
+ raise ValueError("H5 numerical software differs from parent")
128
+
129
+
130
+ def reference_contract(parent, world, old_arrays):
131
+ hashes = {}
132
+ for chain, name in enumerate(CHAINS):
133
+ pair = edit_pair(world, chain)
134
+ assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096
135
+ e, r = sampling_stream(world.seed, chain)
136
+ for scope in ("mlp", "all"):
137
+ dest = parent / "edits" / f"{name}-exception-{scope}"
138
+ with np.load(dest / "sets.npz") as actual:
139
+ for key, value in pair.items():
140
+ np.testing.assert_array_equal(actual[key], value)
141
+ np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"])
142
+ np.testing.assert_array_equal(actual["edit_sampling"], e)
143
+ np.testing.assert_array_equal(actual["replay_sampling"], r)
144
+ points = json.loads((dest / "trajectory.json").read_text())
145
+ if [point["step"] for point in points] != list(CHECKPOINTS):
146
+ raise ValueError("Original MLP/All reference checkpoint grid differs")
147
+ if json.loads((dest / "complete.json").read_text())["status"] != "complete":
148
+ raise ValueError("Original MLP/All reference incomplete")
149
+ for step in CHECKPOINTS:
150
+ with np.load(dest / f"predictions-{step}.npz") as saved:
151
+ arrays = score_arrays(dict(saved), pair["exception"])
152
+ if step == 0:
153
+ for key in ("prediction", "ended"):
154
+ np.testing.assert_array_equal(arrays[key], old_arrays[key])
155
+ for filename in (
156
+ "sets.npz",
157
+ "trajectory.json",
158
+ "complete.json",
159
+ *(f"predictions-{step}.npz" for step in CHECKPOINTS),
160
+ ):
161
+ hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename)
162
+ return hashes
163
+
164
+
165
+ def load_parent(parent):
166
+ config = json.loads((parent / "config.json").read_text())
167
+ world = make_cross_world(config["world"])
168
+ validate_parent_config(config, world)
169
+ with np.load(parent / "predictions-15360.npz") as saved:
170
+ arrays = score_arrays(dict(saved), world.answers)
171
+ references = reference_contract(parent, world, arrays)
172
+ checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False)
173
+ complete = json.loads((parent / "learning-complete.json").read_text())
174
+ if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]:
175
+ raise ValueError("H5 parent checkpoint identity differs")
176
+ if (
177
+ complete["status"] != "complete"
178
+ or state_hash(checkpoint["model"]) != complete["model_sha256"]
179
+ ):
180
+ raise ValueError("H5 parent learning checkpoint is not verified complete")
181
+ provenance = dict(
182
+ directory=str(parent),
183
+ model_sha256=complete["model_sha256"],
184
+ reference_files_sha256=references,
185
+ files_sha256={
186
+ name: file_hash(parent / name)
187
+ for name in (
188
+ "config.json",
189
+ "model-15360.pt",
190
+ "predictions-15360.npz",
191
+ "learning-complete.json",
192
+ )
193
+ },
194
+ )
195
+ return config, world, arrays, checkpoint, provenance
196
+
197
+
198
+ def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device):
199
+ dest = output / f"{CHAINS[chain]}-exception-{SCOPE}"
200
+ if (dest / "complete.json").exists():
201
+ return
202
+ dest.mkdir(parents=True, exist_ok=True)
203
+ model.load_state_dict(baseline)
204
+ selected = select_control_parameters(model)
205
+ frozen = baseline["token.weight"]
206
+ pair = edit_pair(world, chain)
207
+ e, r = sampling_stream(world.seed, chain)
208
+ atomic_numpy_save(
209
+ dest / "sets.npz",
210
+ **pair,
211
+ old_correct=parent_arrays["correct"],
212
+ edit_sampling=e,
213
+ replay_sampling=r,
214
+ )
215
+ new_data = tensor_queries(world, device, pair["exception"])
216
+ model.eval()
217
+ references = []
218
+ with torch.no_grad(), precision(device):
219
+ for begin in range(0, len(pair["replay"]), 256):
220
+ ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device)
221
+ references.append(model(data["tokens"][ids], data["positions"][ids]).detach())
222
+ references = torch.cat(references)
223
+ optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda")
224
+ first, timeline, seconds = 0, [], 0.0
225
+ if (dest / "resume.pt").exists():
226
+ saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False)
227
+ if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name:
228
+ raise ValueError("H5 resume identity differs")
229
+ if not 0 <= saved["step"] <= 512 or saved["step"] % 32:
230
+ raise ValueError("H5 resume step differs")
231
+ if saved["step"]:
232
+ validate_optimizer(saved["optimizer"], saved["step"], 3e-5)
233
+ restore_state(model, optimizer, saved, device)
234
+ first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"]
235
+ for step in range(first, 513):
236
+ if step in CHECKPOINTS:
237
+ if not torch.equal(model.token.weight.detach().cpu(), frozen):
238
+ raise ValueError("Frozen input/output token weights changed")
239
+ if not timeline or timeline[-1]["step"] != step:
240
+ arrays = score_arrays(
241
+ evaluate(model, new_data, pair["exception"]), pair["exception"]
242
+ )
243
+ if step == 0:
244
+ for key in ("prediction", "ended"):
245
+ np.testing.assert_array_equal(arrays[key], parent_arrays[key])
246
+ timeline.append(
247
+ dict(
248
+ step=step,
249
+ edit_seconds=seconds,
250
+ **edit_metrics(world, pair, arrays, parent_arrays["correct"]),
251
+ )
252
+ )
253
+ atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays)
254
+ write_json(dest / "trajectory.json", timeline)
255
+ if step % 32 == 0:
256
+ atomic_torch_save(
257
+ capture_state(
258
+ model,
259
+ optimizer,
260
+ device,
261
+ step=step,
262
+ timeline=timeline,
263
+ seconds=seconds,
264
+ identity_sha256=identity_hash,
265
+ case=dest.name,
266
+ ),
267
+ dest / "resume.pt",
268
+ )
269
+ if step == 512:
270
+ break
271
+ ei = torch.as_tensor(pair["E"][e[step]], device=device)
272
+ ri = torch.as_tensor(pair["replay"][r[step]], device=device)
273
+ choices = torch.as_tensor(r[step], device=device)
274
+ if device.type == "cuda":
275
+ torch.cuda.synchronize(device)
276
+ start = time.perf_counter()
277
+ edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device)
278
+ if device.type == "cuda":
279
+ torch.cuda.synchronize(device)
280
+ seconds += time.perf_counter() - start
281
+ atomic_torch_save(
282
+ dict(model=model.state_dict(), config=model.config_dict(), step=512),
283
+ dest / "model-final.pt",
284
+ )
285
+ write_json(
286
+ dest / "complete.json",
287
+ dict(
288
+ status="complete",
289
+ scope=SCOPE,
290
+ kind="exception",
291
+ chain=CHAINS[chain],
292
+ final=timeline[-1],
293
+ model_sha256=state_hash(model.state_dict()),
294
+ frozen_token_sha256=state_hash({"token.weight": frozen}),
295
+ ),
296
+ )
297
+ print(
298
+ json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True
299
+ )
300
+
301
+
302
+ def run(args):
303
+ validate_study(json.loads(Path(args.config).read_text()))
304
+ parent, output = Path(args.parent).resolve(), Path(args.output).resolve()
305
+ if parent == output or parent in output.parents or output in parent.parents:
306
+ raise ValueError("H5 output must be separate from immutable parent")
307
+ output.mkdir(parents=True, exist_ok=True)
308
+ with (output / ".lock").open("w") as lock:
309
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
310
+ torch.set_num_threads(args.threads)
311
+ config, world, arrays, checkpoint, provenance = load_parent(parent)
312
+ device = torch.device(args.device)
313
+ identity = dict(
314
+ world=world.seed,
315
+ seed=config["seed"],
316
+ condition=config["condition"],
317
+ width=config["model"]["width"],
318
+ study=STUDY,
319
+ sources=control_sources(),
320
+ parent=provenance,
321
+ torch=torch.__version__,
322
+ cuda=torch.version.cuda,
323
+ numpy=np.__version__,
324
+ device_type=device.type,
325
+ )
326
+ path = output / "config.json"
327
+ if path.exists() and json.loads(path.read_text()) != identity:
328
+ raise ValueError("Frozen H5 worker contract changed")
329
+ if not path.exists():
330
+ write_json(path, identity)
331
+ if (output / "complete.json").exists():
332
+ return
333
+ if device.type == "cuda":
334
+ torch.backends.cuda.matmul.allow_tf32 = True
335
+ torch.manual_seed(config["seed"])
336
+ if device.type == "cuda":
337
+ torch.cuda.manual_seed_all(config["seed"])
338
+ model = CausalLM(ModelConfig(**checkpoint["config"])).to(device)
339
+ model.load_state_dict(checkpoint["model"])
340
+ baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()}
341
+ data = tensor_queries(world, device)
342
+ try:
343
+ observed = score_arrays(evaluate(model, data, world.answers), world.answers)
344
+ for key in ("prediction", "ended", "correct"):
345
+ np.testing.assert_array_equal(observed[key], arrays[key])
346
+ for chain in range(2):
347
+ run_case(
348
+ model, baseline, data, world, arrays, chain, output, file_hash(path), device
349
+ )
350
+ write_json(
351
+ output / "complete.json",
352
+ dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()),
353
+ )
354
+ except Exception as error:
355
+ write_json(
356
+ output / "failure.json",
357
+ dict(type=type(error).__name__, message=str(error), time=time.time()),
358
+ )
359
+ raise
360
+
361
+
362
+ def main():
363
+ parser = argparse.ArgumentParser(description=__doc__)
364
+ parser.add_argument("--parent", required=True)
365
+ parser.add_argument("--output", required=True)
366
+ parser.add_argument("--config", default="configs/bios-readout-control-v1.json")
367
+ parser.add_argument("--device", default="cuda")
368
+ parser.add_argument("--threads", type=int, default=2)
369
+ run(parser.parse_args())
370
+
371
+
372
+ if __name__ == "__main__":
373
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_relation_response.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A paired four-cell test of which fact controls a composite answer.
2
+
3
+ The editor is unchanged. Derivative probes use answer contrasts, never a
4
+ composite target loss. Isolated directions preserve the OTHER direct query's
5
+ two a/c and b/c contrasts to first order, not its entire output distribution.
6
+ """
7
+
8
+ from dataclasses import replace
9
+
10
+ import torch
11
+
12
+ from .bios_direction import Suffix
13
+ from .bios_direction_cross import cross_tasks
14
+
15
+ CELLS = ("aa", "ab", "ba", "bb")
16
+ LAYER = 4
17
+
18
+
19
+ def factorial_tasks(world, seed, device):
20
+ """Rows select root targets; columns select personal targets; a/b stay fixed."""
21
+ originals = cross_tasks(world, seed, device)
22
+ result = []
23
+ for pair_index in range(6):
24
+ base = originals[2 * pair_index]
25
+ for cell in CELLS:
26
+ labels, tokens = base.labels.clone(), base.tokens.clone()
27
+ root, actual = base.sets["E"]
28
+ labels[root, 0] = base.metadata[cell[0]]
29
+ labels[actual, 0] = base.metadata[cell[1]]
30
+ labels[base.sets["D"], 0] = base.metadata[cell[0]]
31
+ rows = torch.arange(len(tokens), device=tokens.device)
32
+ tokens[rows, base.positions[:, 0] + 1] = labels[:, 0]
33
+ metadata = dict(
34
+ base.metadata,
35
+ cell=cell,
36
+ pair_index=pair_index,
37
+ kind="coherent" if cell[0] == cell[1] else "independent",
38
+ root_target=base.metadata[cell[0]],
39
+ actual_target=base.metadata[cell[1]],
40
+ )
41
+ result.append(
42
+ replace(
43
+ base,
44
+ name=base.name.rsplit("-", 1)[0] + "-" + cell,
45
+ labels=labels,
46
+ tokens=tokens,
47
+ metadata=metadata,
48
+ )
49
+ )
50
+ return result
51
+
52
+
53
+ def check_reused_task(task, manifest):
54
+ """Compare actual information, including teacher-forced EOS prefixes."""
55
+ current = task.manifest()
56
+ for key in ("sets", "labels", "old_labels", "tokens_sha256"):
57
+ assert current[key] == manifest[key], key
58
+ for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"):
59
+ assert current["metadata"][key] == manifest["metadata"][key], key
60
+
61
+
62
+ def make_probe(model, task):
63
+ ids = task.sets["E"] + task.sets["D_focal"]
64
+ positions = task.positions[ids, :1]
65
+ tokens = task.tokens[ids, :5].clone()
66
+ # No desired answer is present even at masked future positions.
67
+ tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0)
68
+ return Suffix(model, LAYER, tokens, positions)
69
+
70
+
71
+ def values(probe, weight, metadata):
72
+ logits = probe(weight[None])[0, :, 0]
73
+ a, b, c = (metadata[k] for k in ("a", "b", "c"))
74
+ contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1)
75
+ return logits, contrasts
76
+
77
+
78
+ def derivatives(probe, weight, metadata):
79
+ w = weight.detach().clone().requires_grad_()
80
+ logits, contrasts = values(probe, w, metadata)
81
+ gradients = torch.stack(
82
+ [
83
+ torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0]
84
+ for i in range(3)
85
+ for j in range(2)
86
+ ]
87
+ ).reshape(3, 2, *w.shape)
88
+ return logits.detach(), contrasts.detach(), gradients.detach()
89
+
90
+
91
+ def isolated_directions(gradients):
92
+ """Minimum-norm direct-fact controls; D is excluded from construction.
93
+
94
+ A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5),
95
+ hence its a-b contrast by 1; the other fact has both contrasts fixed.
96
+ """
97
+ g = gradients[:2].flatten(0, 1).flatten(1).double()
98
+ gram = g @ g.T
99
+ eig, vec = torch.linalg.eigh(gram)
100
+ keep = eig > eig[-1].clamp_min(1e-30) * 1e-10
101
+ inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T
102
+ targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device)
103
+ controls = targets.double() @ inverse @ g
104
+ achieved = controls @ g.T
105
+ gd = (gradients[2, 0] - gradients[2, 1]).flatten().double()
106
+ coefficients = controls @ gd
107
+ residual = gd - (gd @ g.T) @ inverse @ g
108
+ summary = {
109
+ "rank": int(keep.sum()),
110
+ "spectrum": eig.cpu().tolist(),
111
+ "control_residual": float((achieved - targets).abs().max()),
112
+ "root_response": float(coefficients[0]),
113
+ "actual_response": float(coefficients[1]),
114
+ "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)),
115
+ "root_control_norm": float(controls[0].norm()),
116
+ "actual_control_norm": float(controls[1].norm()),
117
+ }
118
+ return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary
119
+
120
+
121
+ @torch.no_grad()
122
+ def calibrate_controls(probe, weight, metadata, gradients, magnitudes):
123
+ controls, summary = isolated_directions(gradients)
124
+ baseline_logits, baseline = values(probe, weight, metadata)
125
+ rows = []
126
+ if summary["control_residual"] > 1e-5:
127
+ return summary, rows
128
+ for index, name in enumerate(("root", "actual")):
129
+ for magnitude in magnitudes:
130
+ for sign in (-1, 1):
131
+ delta = sign * magnitude * controls[index]
132
+ cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30)))
133
+ delta = delta * cap
134
+ changed, after = values(probe, weight + delta, metadata)
135
+ observed = after - baseline
136
+ predicted = (gradients.double() * delta.double()).sum((-1, -2))
137
+ other = 1 - index
138
+ logp = baseline_logits.double().log_softmax(-1)
139
+ new_logp = changed.double().log_softmax(-1)
140
+ kl = (logp.exp() * (logp - new_logp)).sum(-1)
141
+ rows.append(
142
+ dict(
143
+ control=name,
144
+ magnitude=magnitude,
145
+ sign=sign,
146
+ cap=cap,
147
+ actual_target_increment=sign * magnitude * cap,
148
+ delta_norm=float(delta.norm()),
149
+ predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(),
150
+ observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(),
151
+ other_ac_bc_drift=float(observed[other].abs().max()),
152
+ other_output_kl=float(kl[other]),
153
+ direct_argmax_changes=int(
154
+ (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum()
155
+ ),
156
+ )
157
+ )
158
+ return summary, rows
159
+
160
+
161
+ def first_adam_update(model, task, config):
162
+ """Exact first-step algebra of the frozen soft-functional Adam editor."""
163
+ ids = task.sets["E"] + task.sets["R"]
164
+ suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids])
165
+ w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_()
166
+ logits = suffix(w[None])[0]
167
+ logp = logits.double().log_softmax(-1)
168
+ labels = task.labels[ids]
169
+ ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1)
170
+ n = len(task.sets["E"])
171
+ # The original-parent KL has exactly zero derivative at the parent.
172
+ loss = ce[:n].mean() + ce[n:].mean()
173
+ gradient = torch.autograd.grad(loss, w)[0]
174
+ m, v = 0.1 * gradient, 0.001 * gradient.square()
175
+ t = torch.ones((), device=w.device)
176
+ raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8)
177
+ return config["lr"] * raw
178
+
179
+
180
+ def factorial_effects(margins):
181
+ aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS)
182
+ return dict(
183
+ intercept=(aa + ab + ba + bb) / 4,
184
+ root=(aa + ab - ba - bb) / 4,
185
+ actual=(aa - ab + ba - bb) / 4,
186
+ interaction=(aa - ab - ba + bb) / 4,
187
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Locked independent-world behavioral confirmation, never a route-mediation claim.
2
+
3
+ The original learning implementation and the audited E39 update implementation
4
+ are called directly. An external prospective lock is mandatory before execution.
5
+ """
6
+
7
+ import argparse
8
+ import fcntl
9
+ import hashlib
10
+ import json
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import torch
16
+
17
+ from .bios_cross import CHAINS, CONDITIONS, make_cross_world
18
+ from .bios_cross_train import learning, source_hashes
19
+ from .bios_data import write_json
20
+ from .bios_organization_train import atomic_numpy_save, state_hash
21
+ from .bios_path_diagnostics import autonomous_two_step
22
+ from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair
23
+ from .bios_shortcut_control import high_exception_world
24
+ from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY
25
+ from .bios_shortcut_edit_v2 import run_case
26
+ from .bios_shortcut_matched_edit import KINDS, PHASES
27
+
28
+ PROTOCOL = "v2.9-shortcut-behavior-confirmation"
29
+ WORLDS = tuple(range(100, 108))
30
+ LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360)
31
+
32
+
33
+ def file_hash(path):
34
+ digest = hashlib.sha256()
35
+ with Path(path).open("rb") as stream:
36
+ while chunk := stream.read(4 * 1024 * 1024):
37
+ digest.update(chunk)
38
+ return digest.hexdigest()
39
+
40
+
41
+ def confirmation_sources():
42
+ directory = Path(__file__).parent
43
+ return {
44
+ **source_hashes(),
45
+ "scripts/prepare_bios_shortcut_confirmation.py": file_hash(
46
+ directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py"
47
+ ),
48
+ **{
49
+ name: file_hash(directory / name)
50
+ for name in (
51
+ "bios_shortcut_confirmation.py",
52
+ "bios_shortcut_confirmation_sets.py",
53
+ "bios_shortcut_control.py",
54
+ "bios_shortcut_matched_edit.py",
55
+ "bios_shortcut_edit_v2.py",
56
+ "bios_cross_continue.py",
57
+ "bios_path_diagnostics.py",
58
+ )
59
+ },
60
+ }
61
+
62
+
63
+ def validate_config(config):
64
+ expected = {
65
+ "protocol": PROTOCOL,
66
+ "worlds": list(WORLDS),
67
+ "seeds": [0, 1],
68
+ "conditions": list(CONDITIONS),
69
+ "phases": list(PHASES),
70
+ "chains": list(CHAINS),
71
+ "supports": [0, 1],
72
+ "width": 256,
73
+ "layers": 8,
74
+ "heads": 4,
75
+ "steps": 15360,
76
+ "checkpoints": list(LEARNING_CHECKPOINTS),
77
+ "lr": 0.0001,
78
+ "documents_per_step": 16,
79
+ "facts_per_document": 10,
80
+ "QA_per_chain_per_step": 20,
81
+ "document_QA_weights": [0.8, 0.2],
82
+ "learning_runs": 96,
83
+ "edit_cases": 768,
84
+ "edit_steps": 512,
85
+ "edit_checkpoints": [0, 32, 128, 512],
86
+ "edit_lr": 0.00003,
87
+ "retention_kl": 1.0,
88
+ "edit_scope": "mlp",
89
+ "edit_mlp_layers": [3, 4, 5],
90
+ "edit_batch": 128,
91
+ "replay_batch": 128,
92
+ "edit_weight_decay": 0.1,
93
+ "E": 39,
94
+ "D": 96,
95
+ "R": 4096,
96
+ "base_world_root": "data/bios-shortcut-confirmation-v1",
97
+ "source_root": "data/bios-source",
98
+ }
99
+ for key, value in expected.items():
100
+ if config.get(key) != value:
101
+ raise ValueError(f"Prospective confirmation contract differs: {key}")
102
+ for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"):
103
+ source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"}
104
+ if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]:
105
+ raise ValueError(f"Imported E39 scientific update differs: {key}")
106
+ if config.get("edit_sampling") != "shared original world932chain stream across supports":
107
+ raise ValueError("The two supports retain the original paired sampling stream")
108
+
109
+
110
+ def validate_frozen_design(config_path, lock_path):
111
+ config = json.loads(Path(config_path).read_text())
112
+ validate_config(config)
113
+ lock = json.loads(Path(lock_path).read_text())
114
+ if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome":
115
+ raise ValueError("A prospective confirmation lock is required")
116
+ if lock["config_sha256"] != file_hash(config_path):
117
+ raise ValueError("Confirmation configuration changed after locking")
118
+ if lock["sources"] != confirmation_sources():
119
+ raise ValueError("Confirmation scientific sources changed after locking")
120
+ environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__}
121
+ if lock["environment"] != environment:
122
+ raise ValueError("Confirmation numerical environment changed after locking")
123
+ if not lock.get("analysis_sources"):
124
+ raise ValueError("The prospective analysis implementation must also be locked")
125
+ root = Path(__file__).resolve().parents[2]
126
+ for relative, checksum in lock["analysis_sources"].items():
127
+ if file_hash(root / relative) != checksum:
128
+ raise ValueError(f"Prospective analysis source changed: {relative}")
129
+ if not lock.get("data_source_files"):
130
+ raise ValueError("Original data source files must be prospectively locked")
131
+ for relative, checksum in lock["data_source_files"].items():
132
+ if file_hash(root / relative) != checksum:
133
+ raise ValueError(f"Original data source changed: {relative}")
134
+ return config, lock
135
+
136
+
137
+ def validate_lock(config_path, lock_path, args):
138
+ config, lock = validate_frozen_design(config_path, lock_path)
139
+ if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda":
140
+ raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision")
141
+ if args.world not in WORLDS or args.seed not in (0, 1):
142
+ raise ValueError("Only the eight reserved worlds and two initializations are allowed")
143
+ if args.phase not in PHASES or args.condition not in CONDITIONS:
144
+ raise ValueError("Condition outside the prospective matrix")
145
+ expected_output = (
146
+ Path(lock["output_root"])
147
+ / args.phase
148
+ / "width-256"
149
+ / f"world-{args.world}-seed-{args.seed}-{args.condition}"
150
+ ).resolve()
151
+ if Path(args.output).resolve() != expected_output:
152
+ raise ValueError("Output differs from the prospective matrix")
153
+ return config, lock
154
+
155
+
156
+ def validate_prepared_world(config, config_path, lock_path, world):
157
+ if world not in WORLDS:
158
+ raise ValueError("Requested world is outside the prospective preparation matrix")
159
+ root = Path(__file__).resolve().parents[2] / config["base_world_root"]
160
+ receipt = json.loads((root / "preparation-audit.json").read_text())
161
+ lock = json.loads(Path(lock_path).read_text())
162
+ if (
163
+ receipt.get("complete") is not True
164
+ or receipt["config_sha256"] != file_hash(config_path)
165
+ or receipt["lock_sha256"] != file_hash(lock_path)
166
+ or receipt["worlds"] != list(WORLDS)
167
+ ):
168
+ raise ValueError("Base worlds lack a complete prospectively locked preparation")
169
+ if receipt.get("source_files_sha256") != lock["data_source_files"]:
170
+ raise ValueError("Prepared world source files differ from the prospective lock")
171
+ filenames = ("world.npz", "metadata.json", "audit.json")
172
+ expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames}
173
+ if set(receipt.get("files_sha256", {})) != expected_files:
174
+ raise ValueError("Prepared world file manifest differs from the prospective matrix")
175
+ for name in filenames:
176
+ relative = f"world-{world}/{name}"
177
+ if receipt["files_sha256"].get(relative) != file_hash(root / relative):
178
+ raise ValueError(f"Prepared world changed: {relative}")
179
+ metadata = json.loads((root / f"world-{world}/metadata.json").read_text())
180
+ if type(metadata.get("seed")) is not int or metadata["seed"] != world:
181
+ raise ValueError("Prepared world metadata seed differs from the requested world")
182
+ return root, receipt
183
+
184
+
185
+ def case_identity(worker_identity, chain, support, kind, pair):
186
+ payload = {
187
+ "worker_identity": worker_identity,
188
+ "chain": chain,
189
+ "support": support,
190
+ "kind": kind,
191
+ "pair_contract": pair["contract"],
192
+ }
193
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
194
+
195
+
196
+ def expected_weight_artifacts():
197
+ names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS]
198
+ names.append("learning/resume.pt")
199
+ names.extend(
200
+ f"edits/support-{support}/{chain}-{kind}-mlp/{filename}"
201
+ for support in (0, 1)
202
+ for chain in CHAINS
203
+ for kind in KINDS
204
+ for filename in ("model-final.pt", "resume.pt")
205
+ )
206
+ return names
207
+
208
+
209
+ def scientific_artifacts(output):
210
+ for relative in expected_weight_artifacts():
211
+ if not (output / relative).is_file():
212
+ raise ValueError(f"Required confirmation weight artifact is missing: {relative}")
213
+ paths = [output / "launch-contract.json", output / "manipulation.npz"]
214
+ paths.extend(p for p in (output / "learning").iterdir() if p.is_file())
215
+ paths.extend(p for p in (output / "edits").rglob("*") if p.is_file())
216
+ return {
217
+ str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)}
218
+ for p in sorted(paths)
219
+ }
220
+
221
+
222
+ def run(args):
223
+ config, _ = validate_lock(args.config, args.lock, args)
224
+ output = Path(args.output).resolve()
225
+ output.mkdir(parents=True, exist_ok=True)
226
+ with (output / ".worker.lock").open("w") as handle:
227
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
228
+ torch.set_num_threads(args.threads)
229
+ base_root, data_receipt = validate_prepared_world(
230
+ config, args.config, args.lock, args.world
231
+ )
232
+ if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
233
+ raise ValueError("A healthy CUDA device with BF16 support is required")
234
+ identity = {
235
+ "protocol": PROTOCOL,
236
+ "world": args.world,
237
+ "seed": args.seed,
238
+ "condition": args.condition,
239
+ "phase": args.phase,
240
+ "config_sha256": file_hash(args.config),
241
+ "preregistration_lock_sha256": file_hash(args.lock),
242
+ "sources": confirmation_sources(),
243
+ "torch": torch.__version__,
244
+ "cuda": torch.version.cuda,
245
+ "numpy": np.__version__,
246
+ "device_type": "cuda",
247
+ "precision": "BF16 autocast; FP32 model and optimizer",
248
+ "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"),
249
+ "world_files_sha256": {
250
+ name: checksum
251
+ for name, checksum in data_receipt["files_sha256"].items()
252
+ if name.startswith(f"world-{args.world}/")
253
+ },
254
+ }
255
+ path = output / "launch-contract.json"
256
+ if path.exists() and json.loads(path.read_text()) != identity:
257
+ raise ValueError("Confirmation worker identity changed")
258
+ if not path.exists():
259
+ write_json(path, identity)
260
+ if (output / "complete.json").exists():
261
+ return
262
+ try:
263
+ low = make_cross_world(args.world, source_root=base_root)
264
+ high, manipulation, selected, donors = high_exception_world(low)
265
+ world = low if args.phase == "low" else high
266
+ pairs = {
267
+ (chain, support): make_confirmation_edit_pair(low, high, chain, support)
268
+ for chain in range(2)
269
+ for support in (0, 1)
270
+ }
271
+ for chain in range(2):
272
+ for key in ("groups", "E", "D", "selected_people"):
273
+ if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size:
274
+ raise ValueError(f"The two supports overlap: {key}")
275
+ atomic_numpy_save(
276
+ output / "manipulation.npz",
277
+ selections=selected,
278
+ donors=donors,
279
+ low_answers=low.answers,
280
+ high_answers=high.answers,
281
+ high_exceptions=high.exceptions,
282
+ )
283
+ study = {
284
+ **config,
285
+ "confirmation_sources": identity["sources"],
286
+ "phase": args.phase,
287
+ "manipulation": manipulation,
288
+ }
289
+ learning_output = output / "learning"
290
+ learning_output.mkdir(exist_ok=True)
291
+ device = torch.device(args.device)
292
+ model, data = learning(args, world, learning_output, study, device)
293
+ with np.load(learning_output / "predictions-15360.npz") as saved:
294
+ baseline_predictions = {
295
+ key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")
296
+ }
297
+ np.testing.assert_array_equal(
298
+ baseline_predictions["correct"],
299
+ (baseline_predictions["prediction"] == world.answers)
300
+ & baseline_predictions["ended"],
301
+ )
302
+ completed = json.loads((learning_output / "learning-complete.json").read_text())
303
+ if completed["model_sha256"] != state_hash(model.state_dict()):
304
+ raise ValueError("Learning baseline differs from completed weights")
305
+ for chain, name in enumerate(CHAINS):
306
+ arrays = autonomous_two_step(model, world, chain, device)
307
+ ids = world.derived_ids[chain]
308
+ arrays.update(
309
+ {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()}
310
+ )
311
+ atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays)
312
+ baseline = {
313
+ key: value.detach().cpu().clone() for key, value in model.state_dict().items()
314
+ }
315
+ identity_hash = file_hash(path)
316
+ for support in (0, 1):
317
+ edit_output = output / "edits" / f"support-{support}"
318
+ for chain in range(2):
319
+ for kind in KINDS:
320
+ run_case(
321
+ model,
322
+ baseline,
323
+ data,
324
+ world,
325
+ pairs[chain, support],
326
+ args.phase,
327
+ kind,
328
+ chain,
329
+ edit_output,
330
+ case_identity(
331
+ identity_hash, chain, support, kind, pairs[chain, support]
332
+ ),
333
+ baseline_predictions,
334
+ device,
335
+ )
336
+ write_json(
337
+ output / "complete.json",
338
+ {
339
+ "status": "complete",
340
+ "protocol": PROTOCOL,
341
+ "learning_steps": 15360,
342
+ "edit_cases": 8,
343
+ "edit_steps": 512,
344
+ "lock_sha256": file_hash(args.lock),
345
+ "artifacts": scientific_artifacts(output),
346
+ "finished": time.time(),
347
+ },
348
+ )
349
+ except Exception as error:
350
+ write_json(
351
+ output / "failure.json",
352
+ {"type": type(error).__name__, "message": str(error), "time": time.time()},
353
+ )
354
+ raise
355
+
356
+
357
+ def main():
358
+ parser = argparse.ArgumentParser(description=__doc__)
359
+ parser.add_argument("--world", type=int, required=True)
360
+ parser.add_argument("--seed", type=int, required=True)
361
+ parser.add_argument("--condition", choices=CONDITIONS, required=True)
362
+ parser.add_argument("--phase", choices=PHASES, required=True)
363
+ parser.add_argument("--config", required=True)
364
+ parser.add_argument("--lock", required=True)
365
+ parser.add_argument("--output", required=True)
366
+ parser.add_argument("--device", default="cuda")
367
+ parser.add_argument("--threads", type=int, default=2)
368
+ run(parser.parse_args())
369
+
370
+
371
+ if __name__ == "__main__":
372
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two prospectively fixed E39 supports; preparation never launches a model.
2
+
3
+ Support zero exactly preserves development selection. Support one uses a
4
+ separate deterministic stream and excludes the first support's entire groups.
5
+ The original E39 audit validates both; all training and target budgets match.
6
+ """
7
+
8
+ import numpy as np
9
+
10
+ from .bios_data import array_hash, rng_for
11
+ from .bios_shortcut_control import audit_high_exception
12
+ from .bios_shortcut_matched_edit import (
13
+ KINDS,
14
+ PHASES,
15
+ U_STRATA,
16
+ audit_matched_edit_pair,
17
+ )
18
+ from .bios_shortcut_matched_edit import (
19
+ make_matched_edit_pair as development_pair,
20
+ )
21
+
22
+ BUDGET = {
23
+ "prevalence_levels": 2,
24
+ "worlds": 8,
25
+ "initializations": 2,
26
+ "organizations": 3,
27
+ "models": 96,
28
+ "chains": 2,
29
+ "update_types": 2,
30
+ "supports_per_chain": 2,
31
+ "scopes": ["mlp"],
32
+ "edit_cases": 768,
33
+ }
34
+
35
+
36
+ def make_confirmation_edit_pair(low, high, chain, support=0):
37
+ """Three roots + 36 actual facts; same IDs and support labels across phases.
38
+
39
+ Each selected group contributes six QA-trained and six QA-heldout people
40
+ who remain ordinary in the high-prevalence world. Coherent assigns all 12
41
+ to the new default. Exception assigns three default/three alternative in
42
+ each split. Histograms match ACROSS all three groups, not within a group.
43
+ """
44
+ if chain not in (0, 1) or support not in (0, 1):
45
+ raise ValueError("Confirmation fixes two chains and two disjoint supports")
46
+ if low.seed != high.seed or low.n_base != high.n_base:
47
+ raise ValueError("Low/high worlds must share their identity and query layout")
48
+ audit_high_exception(low, high)
49
+ first = development_pair(low, high, chain)
50
+ if support == 0:
51
+ first["contract"].update(
52
+ protocol="v2.9-shortcut-behavior-confirmation-E39",
53
+ status="prospectively_fixed_confirmation_support",
54
+ budget=BUDGET.copy(),
55
+ model_checkpoint="width256, independent-world 15360-step low/high learning",
56
+ )
57
+ return first
58
+ eligible_groups = np.setdiff1d(np.arange(64), first["groups"])
59
+ rng = rng_for(low.seed, 931, chain + 2 * support)
60
+ for _ in range(10000):
61
+ groups = rng.choice(eligible_groups, 3, replace=False)
62
+ if len(np.unique(low.defaults[chain, groups])) == 3:
63
+ break
64
+ else:
65
+ raise RuntimeError("Could not find three groups with distinct default cities")
66
+ selected = np.empty((3, 12), dtype=np.int64)
67
+ conflict = np.zeros((3, 12), dtype=bool)
68
+ conflict[:, :3] = conflict[:, 6:9] = True
69
+ targets = {
70
+ f"{phase}_{kind}": world.answers.copy()
71
+ for phase, world in (("low", low), ("high", high))
72
+ for kind in KINDS
73
+ }
74
+ new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]]
75
+ alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]]
76
+ for index, group in enumerate(groups):
77
+ ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain])
78
+ for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])):
79
+ eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)]
80
+ if len(eligible) != 8:
81
+ raise ValueError("Expected eight still-ordinary people in each QA split")
82
+ selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6]
83
+ actual = low.actual_ids[chain, selected[index]]
84
+ derived = low.derived_ids[chain, low.memberships[chain] == group]
85
+ for phase in PHASES:
86
+ for kind in KINDS:
87
+ target = targets[f"{phase}_{kind}"]
88
+ target[low.root_ids[chain, group]] = new_default[index]
89
+ target[derived] = new_default[index]
90
+ target[actual] = new_default[index]
91
+ if kind == "exception":
92
+ target[actual[conflict[index]]] = alternative[index]
93
+ edited_people = selected.ravel()
94
+ selected_people = np.isin(low.memberships[chain], groups)
95
+ original = selected_people & low.exceptions[chain]
96
+ newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain]
97
+ unedited_ordinary = (
98
+ selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people)
99
+ )
100
+ e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]]))
101
+ d = low.derived_ids[chain, selected_people]
102
+ unchanged = np.ones(len(low.answers), dtype=bool)
103
+ unchanged[np.concatenate([e, d])] = False
104
+ affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)]
105
+ original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original])
106
+ newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly])
107
+ relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11])
108
+ strata = np.full(len(low.answers), -1, dtype=np.int64)
109
+ strata[unchanged & original_actual] = 0
110
+ strata[unchanged & newly_actual] = 1
111
+ strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2
112
+ strata[unchanged & ~affected_facts & relevant] = 3
113
+ strata[unchanged & ~affected_facts & ~relevant] = 4
114
+ heldout = []
115
+ for stratum in range(5):
116
+ ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10)))
117
+ heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))])
118
+ heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10)))
119
+ heldout = np.array(sorted(heldout), dtype=np.int64)
120
+ common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers))
121
+ common_pool = np.setdiff1d(common_pool, heldout)
122
+ if len(common_pool) < 4096:
123
+ raise ValueError("Insufficient shared unchanged base facts for R4096")
124
+ replay = rng.choice(common_pool, 4096, replace=False)
125
+ paired_reference = np.sort(low.derived_ids[chain, selected[conflict]])
126
+ pair = {
127
+ **targets,
128
+ "groups": groups,
129
+ "selected_people": selected,
130
+ "alternative_assignments": conflict,
131
+ "new_default": new_default,
132
+ "alternative": alternative,
133
+ "E": e,
134
+ "D": d,
135
+ "E_roots": low.root_ids[chain, groups],
136
+ "E_actual": np.sort(low.actual_ids[chain, edited_people]),
137
+ "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]),
138
+ "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]),
139
+ "D_trained": np.intersect1d(d, low.train_ids[chain]),
140
+ "D_heldout": np.intersect1d(d, low.heldout_ids[chain]),
141
+ "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]),
142
+ "paired_reference_D": paired_reference,
143
+ "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]),
144
+ "exception_conflict_D": paired_reference.copy(),
145
+ "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]),
146
+ "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]),
147
+ "D_original_exception": low.derived_ids[chain, original],
148
+ "D_newly_exception": low.derived_ids[chain, newly],
149
+ "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary],
150
+ "R": replay,
151
+ "U_full": np.flatnonzero(unchanged),
152
+ "U_heldout": heldout,
153
+ "U_strata": strata,
154
+ }
155
+ for phase in PHASES:
156
+ for kind in KINDS:
157
+ target = targets[f"{phase}_{kind}"]
158
+ actual_for_d = target[low.actual_ids[chain, selected_people]]
159
+ pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d]
160
+ pair["contract"] = {
161
+ "protocol": "v2.9-shortcut-behavior-confirmation-E39",
162
+ "world": low.seed,
163
+ "chain": chain,
164
+ "support": support,
165
+ "status": "prospectively_fixed_confirmation_support",
166
+ "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()},
167
+ "model_checkpoint": ("width256, independent-world 15360-step low/high learning"),
168
+ "histogram_matching_scope": (
169
+ "all three groups combined; also separately for trained/heldout QA"
170
+ ),
171
+ "coherent_actuals_per_group": "12 new-default (six in each QA split)",
172
+ "exception_actuals_per_group": (
173
+ "6 new-default + 6 alternative (three + three in each QA split)"
174
+ ),
175
+ "paired_reference_semantics": (
176
+ "same 18 people; conflict only in exception, reference only in coherent"
177
+ ),
178
+ "R_semantics": (
179
+ "4096 identical query IDs with identical original truths "
180
+ "and unchanged under all four targets"
181
+ ),
182
+ "U_semantics": (
183
+ "common query IDs; score each phase against its own truth and old-correct coverage"
184
+ ),
185
+ "U_strata": U_STRATA.copy(),
186
+ "historical_E93_comparable": False,
187
+ "low_truth_sha256": array_hash(low.answers),
188
+ "high_truth_sha256": array_hash(high.answers),
189
+ "array_sha256": {key: array_hash(value) for key, value in pair.items()},
190
+ }
191
+ audit_matched_edit_pair(low, high, chain, pair)
192
+ return pair
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """P3: alter shortcut reliability while preserving marginal answer counts.
2
+
3
+ The archived crossover generator and trainer are imported, never rewritten.
4
+ The two chains are manipulated simultaneously; QA identities remain unchanged.
5
+ """
6
+
7
+ import argparse
8
+ import fcntl
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import time
13
+ from dataclasses import replace
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+
19
+ from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule
20
+ from .bios_cross_train import learning, source_hashes
21
+ from .bios_data import array_hash, rng_for, write_json
22
+ from .bios_organization_train import atomic_numpy_save
23
+
24
+
25
+ def high_exception_world(old):
26
+ """Raise both chains from two to sixteen exceptions per 32-member group."""
27
+ audit(old)
28
+ answers, exceptions = old.answers.copy(), old.exceptions.copy()
29
+ selections = np.empty((2, 64, 14), dtype=np.int64)
30
+ donors = np.empty((2, 14, 64), dtype=np.int64)
31
+ for chain in range(2):
32
+ rng = rng_for(old.seed, 930, chain)
33
+ for group in range(64):
34
+ ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain])
35
+ people = []
36
+ for query_pool in (old.train_ids[chain], old.heldout_ids[chain]):
37
+ eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)]
38
+ people.extend(rng.permutation(eligible)[:7])
39
+ selections[chain, group] = people
40
+ # Every lane contains one ordinary member per group. A city-deranged
41
+ # bijection preserves the histogram exactly, separately in each QA split.
42
+ for lane in range(14):
43
+ for _ in range(10000):
44
+ donor = rng.permutation(64)
45
+ if np.all(old.defaults[chain, donor] != old.defaults[chain]):
46
+ break
47
+ else:
48
+ raise RuntimeError("Could not construct a city-deranged permutation")
49
+ donors[chain, lane] = donor
50
+ selected = selections[chain, :, lane]
51
+ answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]]
52
+ exceptions[chain, selected] = True
53
+ world = replace(old, answers=answers, exceptions=exceptions)
54
+ record = audit_high_exception(old, world)
55
+ record["selection_sha256"] = array_hash(selections)
56
+ record["donors_sha256"] = array_hash(donors)
57
+ return world, record, selections, donors
58
+
59
+
60
+ def audit_high_exception(old, new):
61
+ """Fail if the manipulation changes anything outside its declared contract."""
62
+ allowed = old.actual_ids.ravel()
63
+ unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed)
64
+ np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged])
65
+ for field in (
66
+ "prompts",
67
+ "lengths",
68
+ "relation",
69
+ "person",
70
+ "memberships",
71
+ "defaults",
72
+ "membership_ids",
73
+ "root_ids",
74
+ "actual_ids",
75
+ "derived_ids",
76
+ "train_ids",
77
+ "heldout_ids",
78
+ "city_tokens",
79
+ ):
80
+ np.testing.assert_array_equal(getattr(old, field), getattr(new, field))
81
+ if old.token_labels != new.token_labels:
82
+ raise ValueError("Vocabulary changed")
83
+ records = []
84
+ for chain in range(2):
85
+ ids = old.actual_ids[chain]
86
+ np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids]))
87
+ truth_exception = (
88
+ new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]]
89
+ )
90
+ np.testing.assert_array_equal(truth_exception, new.exceptions[chain])
91
+ if np.any(old.exceptions[chain] & ~new.exceptions[chain]):
92
+ raise ValueError("An original exception was removed")
93
+ for group in range(64):
94
+ members = new.memberships[chain] == group
95
+ if int(new.exceptions[chain, members].sum()) != 16:
96
+ raise ValueError("Expected sixteen exceptions per group")
97
+ for pool in (new.train_ids[chain], new.heldout_ids[chain]):
98
+ people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool))
99
+ if len(people) != 16 or new.exceptions[chain, people].sum() != 8:
100
+ raise ValueError("QA split no longer has eight exceptions per group")
101
+ for pool in (new.train_ids[chain], new.heldout_ids[chain]):
102
+ people = np.flatnonzero(np.isin(new.derived_ids[chain], pool))
103
+ np.testing.assert_array_equal(
104
+ np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]])
105
+ )
106
+ records.append(
107
+ {
108
+ "chain": chain,
109
+ "old_exceptions": int(old.exceptions[chain].sum()),
110
+ "new_exceptions": int(new.exceptions[chain].sum()),
111
+ "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()),
112
+ "answer_histogram_preserved": True,
113
+ "split_histograms_preserved": True,
114
+ }
115
+ )
116
+ for condition in CONDITIONS:
117
+ np.testing.assert_array_equal(documents(old, condition), documents(new, condition))
118
+ np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280))
119
+ return {
120
+ "passed": True,
121
+ "world": old.seed,
122
+ "old_truth_sha256": array_hash(old.answers),
123
+ "new_truth_sha256": array_hash(new.answers),
124
+ "prompts_sha256": array_hash(new.prompts),
125
+ "chains": records,
126
+ "changed_total": int((old.answers != new.answers).sum()),
127
+ "document_identities_and_QA_split_preserved": True,
128
+ }
129
+
130
+
131
+ def shortcut_sources():
132
+ diagnostic = Path(__file__).with_name("bios_path_diagnostics.py")
133
+ return {
134
+ **source_hashes(),
135
+ Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
136
+ diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(),
137
+ }
138
+
139
+
140
+ def run(args):
141
+ out = Path(args.output).resolve()
142
+ out.mkdir(parents=True, exist_ok=True)
143
+ with (out / ".lock").open("w") as lock:
144
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
145
+ study = json.loads(Path(args.config).read_text())
146
+ if study["width"] != 256 or study["steps"] != 15360:
147
+ raise ValueError("P3 freezes width 256 and 15360 steps")
148
+ old = make_cross_world(args.world)
149
+ world, manipulation, selected, donors = high_exception_world(old)
150
+ contract = {
151
+ "protocol": "v2.8-p3-shortcut-reliability",
152
+ "study": study,
153
+ "world": args.world,
154
+ "seed": args.seed,
155
+ "condition": args.condition,
156
+ "sources": shortcut_sources(),
157
+ "manipulation": manipulation,
158
+ "environment": {
159
+ "torch": torch.__version__,
160
+ "cuda": torch.version.cuda,
161
+ "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"),
162
+ },
163
+ }
164
+ contract_path = out / "launch-contract.json"
165
+ if contract_path.exists():
166
+ frozen = json.loads(contract_path.read_text())
167
+ for key in (
168
+ "protocol",
169
+ "study",
170
+ "world",
171
+ "seed",
172
+ "condition",
173
+ "sources",
174
+ "manipulation",
175
+ ):
176
+ if frozen[key] != contract[key]:
177
+ raise ValueError(f"Frozen shortcut contract changed: {key}")
178
+ else:
179
+ write_json(contract_path, contract)
180
+ atomic_numpy_save(
181
+ out / "manipulation.npz",
182
+ selections=selected,
183
+ donors=donors,
184
+ old_answers=old.answers,
185
+ answers=world.answers,
186
+ exceptions=world.exceptions,
187
+ train_ids=world.train_ids,
188
+ heldout_ids=world.heldout_ids,
189
+ )
190
+ if (out / "complete.json").exists():
191
+ return
192
+ # Include adapter provenance in the archived trainer's own run identity.
193
+ study = {**study, "shortcut_contract": contract["sources"]}
194
+ torch.set_num_threads(args.threads)
195
+ try:
196
+ from .bios_path_diagnostics import autonomous_two_step
197
+
198
+ device = torch.device(args.device)
199
+ model, _ = learning(args, world, out, study, device)
200
+ with np.load(out / f"predictions-{study['steps']}.npz") as saved:
201
+ direct = {k: saved[k] for k in ("prediction", "ended", "correct")}
202
+ for chain, name in enumerate(("company", "project")):
203
+ arrays = autonomous_two_step(model, world, chain, device)
204
+ ids = world.derived_ids[chain]
205
+ arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()})
206
+ atomic_numpy_save(out / f"two-step-{name}.npz", **arrays)
207
+ write_json(
208
+ out / "complete.json",
209
+ {
210
+ "status": "complete",
211
+ "phase": "P3-learning-only",
212
+ "learning_steps": study["steps"],
213
+ "edit_cases": 0,
214
+ "finished": time.time(),
215
+ },
216
+ )
217
+ except Exception as error:
218
+ write_json(
219
+ out / "failure.json",
220
+ {
221
+ "type": type(error).__name__,
222
+ "message": str(error),
223
+ "time": time.time(),
224
+ },
225
+ )
226
+ raise
227
+
228
+
229
+ def main():
230
+ parser = argparse.ArgumentParser(description=__doc__)
231
+ parser.add_argument("--world", type=int, required=True)
232
+ parser.add_argument("--seed", type=int, required=True)
233
+ parser.add_argument("--condition", choices=CONDITIONS, required=True)
234
+ parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json")
235
+ parser.add_argument("--output", required=True)
236
+ parser.add_argument("--device", default="cuda")
237
+ parser.add_argument("--threads", type=int, default=2)
238
+ run(parser.parse_args())
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepared, resumable E39 MLP edits of matched low/high 15360-step parents."""
2
+
3
+ import argparse
4
+ import fcntl
5
+ import hashlib
6
+ import json
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from .bios_cross import CHAINS, CONDITIONS, make_cross_world
14
+ from .bios_cross_continue import (
15
+ capture_state,
16
+ edit_update,
17
+ file_hash,
18
+ restore_state,
19
+ validate_optimizer,
20
+ )
21
+ from .bios_cross_train import evaluate, source_hashes, tensor_queries
22
+ from .bios_data import array_hash, rng_for, write_json
23
+ from .bios_model import CausalLM, ModelConfig, select_parameters
24
+ from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash
25
+ from .bios_shortcut_control import high_exception_world, shortcut_sources
26
+ from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair
27
+ from .bios_train import precision
28
+
29
+ CHECKPOINTS = (0, 32, 128, 512)
30
+ STUDY = {
31
+ "protocol": "v2.8-p3-shortcut-matched-E39",
32
+ "width": 256,
33
+ "parent_step": 15360,
34
+ "phases": list(PHASES),
35
+ "worlds": [0, 1],
36
+ "seeds": [0, 1],
37
+ "conditions": list(CONDITIONS),
38
+ "chains": list(CHAINS),
39
+ "kinds": list(KINDS),
40
+ "scope": "mlp",
41
+ "mlp_layers": [3, 4, 5],
42
+ "lr": 0.00003,
43
+ "weight_decay": 0.1,
44
+ "edit_batch": 128,
45
+ "replay_batch": 128,
46
+ "retention_kl": 1.0,
47
+ "clip_norm": 1.0,
48
+ "steps": 512,
49
+ "checkpoints": list(CHECKPOINTS),
50
+ "resume_every": 32,
51
+ "models": 24,
52
+ "edit_cases": 96,
53
+ "E": 39,
54
+ "D": 96,
55
+ "R": 4096,
56
+ "primary_reference_D": 18,
57
+ "primary_reference_D_heldout": 9,
58
+ "status": "prepared conditional branch; no best-step selection",
59
+ }
60
+
61
+
62
+ def validate_study(study):
63
+ if study != STUDY:
64
+ raise ValueError("E39 editing configuration differs from the frozen prepared contract")
65
+
66
+
67
+ def editing_sources():
68
+ directory = Path(__file__).parent
69
+ return {
70
+ **source_hashes(),
71
+ **{
72
+ name: hashlib.sha256((directory / name).read_bytes()).hexdigest()
73
+ for name in (
74
+ "bios_cross_continue.py",
75
+ "bios_shortcut_control.py",
76
+ "bios_shortcut_matched_edit.py",
77
+ "bios_shortcut_edit.py",
78
+ )
79
+ },
80
+ }
81
+
82
+
83
+ def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096):
84
+ """No phase, organization, initialization, or update-type dependence."""
85
+ rng = rng_for(world_seed, 932, chain)
86
+ return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch))
87
+
88
+
89
+ def score_arrays(arrays, truth):
90
+ if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")):
91
+ raise ValueError("Prediction shape mismatch")
92
+ if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_:
93
+ raise ValueError("EOS and correctness must be Boolean arrays")
94
+ np.testing.assert_array_equal(
95
+ arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"]
96
+ )
97
+ return arrays
98
+
99
+
100
+ def query_metrics(correct, ids):
101
+ n = len(ids)
102
+ count = int(correct[ids].sum())
103
+ return {"n": n, "correct": count, "accuracy": count / n if n else None}
104
+
105
+
106
+ def retention_metrics(correct, old_correct, ids):
107
+ n = len(ids)
108
+ known_ids = ids[old_correct[ids]]
109
+ broken = int((~correct[known_ids]).sum())
110
+ return {
111
+ "n": n,
112
+ "known": len(known_ids),
113
+ "coverage": len(known_ids) / n if n else None,
114
+ "broken": broken,
115
+ "damage": broken / len(known_ids) if len(known_ids) else None,
116
+ }
117
+
118
+
119
+ def edit_metrics(pair, phase, kind, arrays, old_correct):
120
+ correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"]
121
+ if old_correct.shape != correct.shape or old_correct.dtype != np.bool_:
122
+ raise ValueError("Old-correct coverage array mismatch")
123
+ result = {
124
+ key: query_metrics(correct, pair[key])
125
+ for key in (
126
+ "E",
127
+ "E_roots",
128
+ "E_actual",
129
+ "D",
130
+ "D_trained",
131
+ "D_heldout",
132
+ "paired_reference_D",
133
+ "paired_reference_D_heldout",
134
+ "D_edited_actual",
135
+ "D_edited_aligned",
136
+ "D_original_exception",
137
+ "D_newly_exception",
138
+ "D_remaining_ordinary_unedited",
139
+ )
140
+ }
141
+ if kind == "exception":
142
+ result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"])
143
+ result["exception_conflict_D_heldout"] = query_metrics(
144
+ correct, pair["exception_conflict_D_heldout"]
145
+ )
146
+ result["factual_conflict_D"] = query_metrics(
147
+ correct, pair[f"{phase}_{kind}_factual_conflict_D"]
148
+ )
149
+ for pool in ("U_full", "U_heldout"):
150
+ ids = pair[pool]
151
+ result[pool] = {
152
+ **retention_metrics(correct, old_correct, ids),
153
+ "strata": {
154
+ str(group): retention_metrics(
155
+ correct, old_correct, ids[pair["U_strata"][ids] == group]
156
+ )
157
+ for group in range(5)
158
+ },
159
+ }
160
+ return result
161
+
162
+
163
+ def load_parent(parent, phase):
164
+ config = json.loads((parent / "config.json").read_text())
165
+ expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128)
166
+ if config["model"] != expected_model or config["study"]["steps"] != 15360:
167
+ raise ValueError("E39 requires original width256/15360 parents, never P2 continuations")
168
+ if any(
169
+ config["study"][key] != value
170
+ for key, value in {
171
+ "lr": 1e-4,
172
+ "documents_per_step": 16,
173
+ "facts_per_document": 10,
174
+ "QA_per_chain_per_step": 20,
175
+ "document_QA_weights": [0.8, 0.2],
176
+ }.items()
177
+ ):
178
+ raise ValueError("E39 parent exposure or learning budget differs")
179
+ if (
180
+ config["world"] not in (0, 1)
181
+ or config["seed"] not in (0, 1)
182
+ or config["condition"] not in CONDITIONS
183
+ ):
184
+ raise ValueError("Parent is outside the fixed development matrix")
185
+ if config["sources"] != source_hashes():
186
+ raise ValueError("Parent frozen trainer sources changed")
187
+ if config["torch"] != torch.__version__ or config["numpy"] != np.__version__:
188
+ raise ValueError("Parent numerical software differs")
189
+ if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover":
190
+ raise ValueError("Low parent is not an original unrestricted-context run")
191
+ if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources():
192
+ raise ValueError("High parent manipulation/source provenance changed")
193
+ low = make_cross_world(config["world"])
194
+ high, _, _, _ = high_exception_world(low)
195
+ world = low if phase == "low" else high
196
+ if config["truth_sha256"] != array_hash(world.answers):
197
+ raise ValueError("Parent truth differs from its declared prevalence phase")
198
+ with np.load(parent / "predictions-15360.npz") as saved:
199
+ predictions = score_arrays(
200
+ {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")},
201
+ world.answers,
202
+ )
203
+ checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False)
204
+ complete = json.loads((parent / "learning-complete.json").read_text())
205
+ if (
206
+ checkpoint["step"] != 15360
207
+ or checkpoint["config"] != config["model"]
208
+ or complete["status"] != "complete"
209
+ ):
210
+ raise ValueError("Parent learning has not completed the specified checkpoint")
211
+ if state_hash(checkpoint["model"]) != complete["model_sha256"]:
212
+ raise ValueError("Parent checkpoint differs from completed learning weights")
213
+ provenance = {
214
+ "directory": str(parent),
215
+ "files_sha256": {
216
+ name: file_hash(parent / name)
217
+ for name in (
218
+ "config.json",
219
+ "model-15360.pt",
220
+ "predictions-15360.npz",
221
+ "learning-complete.json",
222
+ )
223
+ },
224
+ "model_sha256": complete["model_sha256"],
225
+ }
226
+ return config, checkpoint, predictions, low, high, world, provenance
227
+
228
+
229
+ def run_case(
230
+ model,
231
+ baseline,
232
+ data,
233
+ world,
234
+ pair,
235
+ phase,
236
+ kind,
237
+ chain,
238
+ output,
239
+ identity_hash,
240
+ parent_predictions,
241
+ device,
242
+ ):
243
+ dest = output / f"{CHAINS[chain]}-{kind}-mlp"
244
+ if (dest / "complete.json").exists():
245
+ return
246
+ dest.mkdir(parents=True, exist_ok=True)
247
+ model.load_state_dict(baseline)
248
+ selected = select_parameters(model, "mlp", 3)
249
+ e_choices, r_choices = sampling_stream(world.seed, chain)
250
+ saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)}
251
+ saved_sets.update(
252
+ old_correct=parent_predictions["correct"],
253
+ edit_sampling=e_choices,
254
+ replay_sampling=r_choices,
255
+ )
256
+ atomic_numpy_save(dest / "sets.npz", **saved_sets)
257
+ write_json(dest / "data-contract.json", pair["contract"])
258
+ target = pair[f"{phase}_{kind}"]
259
+ new_data = tensor_queries(world, device, target)
260
+ model.eval()
261
+ references = []
262
+ with torch.no_grad(), precision(device):
263
+ for begin in range(0, len(pair["R"]), 256):
264
+ ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device)
265
+ references.append(model(data["tokens"][ids], data["positions"][ids]).detach())
266
+ references = torch.cat(references)
267
+ optimizer = torch.optim.AdamW(
268
+ selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda"
269
+ )
270
+ first, timeline, seconds = 0, [], 0.0
271
+ if (dest / "resume.pt").exists():
272
+ saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False)
273
+ if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name:
274
+ raise ValueError("E39 resume identity mismatch")
275
+ if not 0 <= saved["step"] <= 512 or saved["step"] % 32:
276
+ raise ValueError("E39 resume step mismatch")
277
+ if saved["step"]:
278
+ validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"])
279
+ restore_state(model, optimizer, saved, device)
280
+ first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"]
281
+ for step in range(first, 513):
282
+ if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step):
283
+ arrays = evaluate(model, new_data, target)
284
+ if step == 0:
285
+ for key in ("prediction", "ended"):
286
+ np.testing.assert_array_equal(arrays[key], parent_predictions[key])
287
+ point = {
288
+ "step": step,
289
+ "edit_seconds": seconds,
290
+ **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]),
291
+ }
292
+ timeline.append(point)
293
+ atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays)
294
+ write_json(dest / "trajectory.json", timeline)
295
+ if step % 32 == 0:
296
+ atomic_torch_save(
297
+ capture_state(
298
+ model,
299
+ optimizer,
300
+ device,
301
+ step=step,
302
+ timeline=timeline,
303
+ seconds=seconds,
304
+ identity_sha256=identity_hash,
305
+ case=dest.name,
306
+ ),
307
+ dest / "resume.pt",
308
+ )
309
+ if step == 512:
310
+ break
311
+ ei = torch.as_tensor(pair["E"][e_choices[step]], device=device)
312
+ ri = torch.as_tensor(pair["R"][r_choices[step]], device=device)
313
+ choices = torch.as_tensor(r_choices[step], device=device)
314
+ if device.type == "cuda":
315
+ torch.cuda.synchronize(device)
316
+ started = time.perf_counter()
317
+ edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device)
318
+ if device.type == "cuda":
319
+ torch.cuda.synchronize(device)
320
+ seconds += time.perf_counter() - started
321
+ atomic_torch_save(
322
+ {"model": model.state_dict(), "config": model.config_dict(), "step": 512},
323
+ dest / "model-final.pt",
324
+ )
325
+ write_json(
326
+ dest / "complete.json",
327
+ {
328
+ "status": "complete",
329
+ "phase": phase,
330
+ "chain": CHAINS[chain],
331
+ "kind": kind,
332
+ "scope": "mlp",
333
+ "final": timeline[-1],
334
+ "model_sha256": state_hash(model.state_dict()),
335
+ },
336
+ )
337
+ print(
338
+ json.dumps(
339
+ {
340
+ "event": "E39_edit_complete",
341
+ "case": dest.name,
342
+ "E": timeline[-1]["E"]["accuracy"],
343
+ "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"],
344
+ }
345
+ ),
346
+ flush=True,
347
+ )
348
+
349
+
350
+ def run(args):
351
+ validate_study(json.loads(Path(args.config).read_text()))
352
+ parent, output = Path(args.parent).resolve(), Path(args.output).resolve()
353
+ if parent == output or parent in output.parents or output in parent.parents:
354
+ raise ValueError("E39 output must be separate from its immutable parent")
355
+ output.mkdir(parents=True, exist_ok=True)
356
+ with (output / ".lock").open("w") as lock:
357
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
358
+ torch.set_num_threads(args.threads)
359
+ config, checkpoint, predictions, low, high, world, provenance = load_parent(
360
+ parent, args.phase
361
+ )
362
+ pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)]
363
+ identity = {
364
+ "phase": args.phase,
365
+ "world": world.seed,
366
+ "seed": config["seed"],
367
+ "condition": config["condition"],
368
+ "study": STUDY,
369
+ "sources": editing_sources(),
370
+ "parent": provenance,
371
+ "data_contracts": [pair["contract"] for pair in pairs],
372
+ "torch": torch.__version__,
373
+ "cuda": torch.version.cuda,
374
+ "numpy": np.__version__,
375
+ "device_type": torch.device(args.device).type,
376
+ }
377
+ identity_path = output / "config.json"
378
+ if identity_path.exists() and json.loads(identity_path.read_text()) != identity:
379
+ raise ValueError("E39 editing identity or sources changed")
380
+ if not identity_path.exists():
381
+ write_json(identity_path, identity)
382
+ if (output / "complete.json").exists():
383
+ return
384
+ device = torch.device(args.device)
385
+ if device.type == "cuda":
386
+ torch.backends.cuda.matmul.allow_tf32 = True
387
+ torch.manual_seed(config["seed"])
388
+ if device.type == "cuda":
389
+ torch.cuda.manual_seed_all(config["seed"])
390
+ model = CausalLM(ModelConfig(**checkpoint["config"])).to(device)
391
+ model.load_state_dict(checkpoint["model"])
392
+ data = tensor_queries(world, device)
393
+ try:
394
+ baseline = {
395
+ key: value.detach().cpu().clone() for key, value in model.state_dict().items()
396
+ }
397
+ observed = evaluate(model, data, world.answers)
398
+ for key in ("prediction", "ended", "correct"):
399
+ np.testing.assert_array_equal(observed[key], predictions[key])
400
+ for chain in range(2):
401
+ for kind in KINDS:
402
+ run_case(
403
+ model,
404
+ baseline,
405
+ data,
406
+ world,
407
+ pairs[chain],
408
+ args.phase,
409
+ kind,
410
+ chain,
411
+ output,
412
+ file_hash(identity_path),
413
+ predictions,
414
+ device,
415
+ )
416
+ write_json(
417
+ output / "complete.json",
418
+ {
419
+ "status": "complete",
420
+ "phase": args.phase,
421
+ "edit_cases": 4,
422
+ "steps": 512,
423
+ "finished": time.time(),
424
+ },
425
+ )
426
+ except Exception as error:
427
+ write_json(
428
+ output / "failure.json",
429
+ {"type": type(error).__name__, "message": str(error), "time": time.time()},
430
+ )
431
+ raise
432
+
433
+
434
+ def main():
435
+ parser = argparse.ArgumentParser(description=__doc__)
436
+ parser.add_argument("--parent", required=True)
437
+ parser.add_argument("--phase", choices=PHASES, required=True)
438
+ parser.add_argument("--output", required=True)
439
+ parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json")
440
+ parser.add_argument("--device", default="cuda")
441
+ parser.add_argument("--threads", type=int, default=2)
442
+ run(parser.parse_args())
443
+
444
+
445
+ if __name__ == "__main__":
446
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepared, resumable E39 MLP edits of matched low/high 15360-step parents."""
2
+
3
+ import argparse
4
+ import fcntl
5
+ import hashlib
6
+ import json
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from .bios_cross import CHAINS, CONDITIONS, make_cross_world
14
+ from .bios_cross_continue import (
15
+ capture_state,
16
+ edit_update,
17
+ file_hash,
18
+ restore_state,
19
+ validate_optimizer,
20
+ )
21
+ from .bios_cross_train import evaluate, source_hashes, tensor_queries
22
+ from .bios_data import array_hash, rng_for, write_json
23
+ from .bios_model import CausalLM, ModelConfig, select_parameters
24
+ from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash
25
+ from .bios_shortcut_control import high_exception_world, shortcut_sources
26
+ from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair
27
+ from .bios_train import precision
28
+
29
+ CHECKPOINTS = (0, 32, 128, 512)
30
+ STUDY = {
31
+ "protocol": "v2.8-p3-shortcut-matched-E39",
32
+ "width": 256,
33
+ "parent_step": 15360,
34
+ "phases": list(PHASES),
35
+ "worlds": [0, 1],
36
+ "seeds": [0, 1],
37
+ "conditions": list(CONDITIONS),
38
+ "chains": list(CHAINS),
39
+ "kinds": list(KINDS),
40
+ "scope": "mlp",
41
+ "mlp_layers": [3, 4, 5],
42
+ "lr": 0.00003,
43
+ "weight_decay": 0.1,
44
+ "edit_batch": 128,
45
+ "replay_batch": 128,
46
+ "retention_kl": 1.0,
47
+ "clip_norm": 1.0,
48
+ "steps": 512,
49
+ "checkpoints": list(CHECKPOINTS),
50
+ "resume_every": 32,
51
+ "models": 24,
52
+ "edit_cases": 96,
53
+ "E": 39,
54
+ "D": 96,
55
+ "R": 4096,
56
+ "primary_reference_D": 18,
57
+ "primary_reference_D_heldout": 9,
58
+ "status": "prepared conditional branch; no best-step selection",
59
+ }
60
+
61
+
62
+ def validate_study(study):
63
+ if study != STUDY:
64
+ raise ValueError("E39 editing configuration differs from the frozen prepared contract")
65
+
66
+
67
+ def editing_sources():
68
+ directory = Path(__file__).parent
69
+ return {
70
+ **source_hashes(),
71
+ **{
72
+ name: hashlib.sha256((directory / name).read_bytes()).hexdigest()
73
+ for name in (
74
+ "bios_cross_continue.py",
75
+ "bios_shortcut_control.py",
76
+ "bios_shortcut_matched_edit.py",
77
+ "bios_shortcut_edit_v2.py",
78
+ )
79
+ },
80
+ }
81
+
82
+
83
+ def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096):
84
+ """No phase, organization, initialization, or update-type dependence."""
85
+ rng = rng_for(world_seed, 932, chain)
86
+ return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch))
87
+
88
+
89
+ def score_arrays(arrays, truth):
90
+ if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")):
91
+ raise ValueError("Prediction shape mismatch")
92
+ if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_:
93
+ raise ValueError("EOS and correctness must be Boolean arrays")
94
+ np.testing.assert_array_equal(
95
+ arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"]
96
+ )
97
+ return arrays
98
+
99
+
100
+ def query_metrics(correct, ids):
101
+ n = len(ids)
102
+ count = int(correct[ids].sum())
103
+ return {"n": n, "correct": count, "accuracy": count / n if n else None}
104
+
105
+
106
+ def retention_metrics(correct, old_correct, ids):
107
+ n = len(ids)
108
+ known_ids = ids[old_correct[ids]]
109
+ broken = int((~correct[known_ids]).sum())
110
+ return {
111
+ "n": n,
112
+ "known": len(known_ids),
113
+ "coverage": len(known_ids) / n if n else None,
114
+ "broken": broken,
115
+ "damage": broken / len(known_ids) if len(known_ids) else None,
116
+ }
117
+
118
+
119
+ def edit_metrics(pair, phase, kind, arrays, old_correct):
120
+ correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"]
121
+ if old_correct.shape != correct.shape or old_correct.dtype != np.bool_:
122
+ raise ValueError("Old-correct coverage array mismatch")
123
+ result = {
124
+ key: query_metrics(correct, pair[key])
125
+ for key in (
126
+ "E",
127
+ "E_roots",
128
+ "E_actual",
129
+ "D",
130
+ "D_trained",
131
+ "D_heldout",
132
+ "paired_reference_D",
133
+ "paired_reference_D_heldout",
134
+ "D_edited_actual",
135
+ "D_edited_aligned",
136
+ "D_original_exception",
137
+ "D_newly_exception",
138
+ "D_remaining_ordinary_unedited",
139
+ )
140
+ }
141
+ if kind == "exception":
142
+ result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"])
143
+ result["exception_conflict_D_heldout"] = query_metrics(
144
+ correct, pair["exception_conflict_D_heldout"]
145
+ )
146
+ result["factual_conflict_D"] = query_metrics(
147
+ correct, pair[f"{phase}_{kind}_factual_conflict_D"]
148
+ )
149
+ for pool in ("U_full", "U_heldout"):
150
+ ids = pair[pool]
151
+ result[pool] = {
152
+ **retention_metrics(correct, old_correct, ids),
153
+ "strata": {
154
+ str(group): retention_metrics(
155
+ correct, old_correct, ids[pair["U_strata"][ids] == group]
156
+ )
157
+ for group in range(5)
158
+ },
159
+ }
160
+ return result
161
+
162
+
163
+ def load_parent(parent, phase):
164
+ config = json.loads((parent / "config.json").read_text())
165
+ low = make_cross_world(config["world"])
166
+ expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128)
167
+ if config["model"] != expected_model or config["study"]["steps"] != 15360:
168
+ raise ValueError("E39 requires original width256/15360 parents, never P2 continuations")
169
+ if any(
170
+ config["study"][key] != value
171
+ for key, value in {
172
+ "lr": 1e-4,
173
+ "documents_per_step": 16,
174
+ "facts_per_document": 10,
175
+ "QA_per_chain_per_step": 20,
176
+ "document_QA_weights": [0.8, 0.2],
177
+ }.items()
178
+ ):
179
+ raise ValueError("E39 parent exposure or learning budget differs")
180
+ if (
181
+ config["world"] not in (0, 1)
182
+ or config["seed"] not in (0, 1)
183
+ or config["condition"] not in CONDITIONS
184
+ ):
185
+ raise ValueError("Parent is outside the fixed development matrix")
186
+ if config["sources"] != source_hashes():
187
+ raise ValueError("Parent frozen trainer sources changed")
188
+ if config["torch"] != torch.__version__ or config["numpy"] != np.__version__:
189
+ raise ValueError("Parent numerical software differs")
190
+ if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover":
191
+ raise ValueError("Low parent is not an original unrestricted-context run")
192
+ if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources():
193
+ raise ValueError("High parent manipulation/source provenance changed")
194
+ high, _, _, _ = high_exception_world(low)
195
+ world = low if phase == "low" else high
196
+ if config["truth_sha256"] != array_hash(world.answers):
197
+ raise ValueError("Parent truth differs from its declared prevalence phase")
198
+ with np.load(parent / "predictions-15360.npz") as saved:
199
+ predictions = score_arrays(
200
+ {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")},
201
+ world.answers,
202
+ )
203
+ checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False)
204
+ complete = json.loads((parent / "learning-complete.json").read_text())
205
+ if (
206
+ checkpoint["step"] != 15360
207
+ or checkpoint["config"] != config["model"]
208
+ or complete["status"] != "complete"
209
+ ):
210
+ raise ValueError("Parent learning has not completed the specified checkpoint")
211
+ if state_hash(checkpoint["model"]) != complete["model_sha256"]:
212
+ raise ValueError("Parent checkpoint differs from completed learning weights")
213
+ provenance = {
214
+ "directory": str(parent),
215
+ "files_sha256": {
216
+ name: file_hash(parent / name)
217
+ for name in (
218
+ "config.json",
219
+ "model-15360.pt",
220
+ "predictions-15360.npz",
221
+ "learning-complete.json",
222
+ )
223
+ },
224
+ "model_sha256": complete["model_sha256"],
225
+ }
226
+ return config, checkpoint, predictions, low, high, world, provenance
227
+
228
+
229
+ def run_case(
230
+ model,
231
+ baseline,
232
+ data,
233
+ world,
234
+ pair,
235
+ phase,
236
+ kind,
237
+ chain,
238
+ output,
239
+ identity_hash,
240
+ parent_predictions,
241
+ device,
242
+ ):
243
+ dest = output / f"{CHAINS[chain]}-{kind}-mlp"
244
+ if (dest / "complete.json").exists():
245
+ return
246
+ dest.mkdir(parents=True, exist_ok=True)
247
+ model.load_state_dict(baseline)
248
+ selected = select_parameters(model, "mlp", 3)
249
+ e_choices, r_choices = sampling_stream(world.seed, chain)
250
+ saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)}
251
+ saved_sets.update(
252
+ old_correct=parent_predictions["correct"],
253
+ edit_sampling=e_choices,
254
+ replay_sampling=r_choices,
255
+ )
256
+ atomic_numpy_save(dest / "sets.npz", **saved_sets)
257
+ write_json(dest / "data-contract.json", pair["contract"])
258
+ target = pair[f"{phase}_{kind}"]
259
+ new_data = tensor_queries(world, device, target)
260
+ model.eval()
261
+ references = []
262
+ with torch.no_grad(), precision(device):
263
+ for begin in range(0, len(pair["R"]), 256):
264
+ ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device)
265
+ references.append(model(data["tokens"][ids], data["positions"][ids]).detach())
266
+ references = torch.cat(references)
267
+ optimizer = torch.optim.AdamW(
268
+ selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda"
269
+ )
270
+ first, timeline, seconds = 0, [], 0.0
271
+ if (dest / "resume.pt").exists():
272
+ saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False)
273
+ if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name:
274
+ raise ValueError("E39 resume identity mismatch")
275
+ if not 0 <= saved["step"] <= 512 or saved["step"] % 32:
276
+ raise ValueError("E39 resume step mismatch")
277
+ if saved["step"]:
278
+ validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"])
279
+ restore_state(model, optimizer, saved, device)
280
+ first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"]
281
+ for step in range(first, 513):
282
+ if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step):
283
+ arrays = evaluate(model, new_data, target)
284
+ if step == 0:
285
+ for key in ("prediction", "ended"):
286
+ np.testing.assert_array_equal(arrays[key], parent_predictions[key])
287
+ point = {
288
+ "step": step,
289
+ "edit_seconds": seconds,
290
+ **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]),
291
+ }
292
+ timeline.append(point)
293
+ atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays)
294
+ write_json(dest / "trajectory.json", timeline)
295
+ if step % 32 == 0:
296
+ atomic_torch_save(
297
+ capture_state(
298
+ model,
299
+ optimizer,
300
+ device,
301
+ step=step,
302
+ timeline=timeline,
303
+ seconds=seconds,
304
+ identity_sha256=identity_hash,
305
+ case=dest.name,
306
+ ),
307
+ dest / "resume.pt",
308
+ )
309
+ if step == 512:
310
+ break
311
+ ei = torch.as_tensor(pair["E"][e_choices[step]], device=device)
312
+ ri = torch.as_tensor(pair["R"][r_choices[step]], device=device)
313
+ choices = torch.as_tensor(r_choices[step], device=device)
314
+ if device.type == "cuda":
315
+ torch.cuda.synchronize(device)
316
+ started = time.perf_counter()
317
+ edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device)
318
+ if device.type == "cuda":
319
+ torch.cuda.synchronize(device)
320
+ seconds += time.perf_counter() - started
321
+ atomic_torch_save(
322
+ {"model": model.state_dict(), "config": model.config_dict(), "step": 512},
323
+ dest / "model-final.pt",
324
+ )
325
+ write_json(
326
+ dest / "complete.json",
327
+ {
328
+ "status": "complete",
329
+ "phase": phase,
330
+ "chain": CHAINS[chain],
331
+ "kind": kind,
332
+ "scope": "mlp",
333
+ "final": timeline[-1],
334
+ "model_sha256": state_hash(model.state_dict()),
335
+ },
336
+ )
337
+ print(
338
+ json.dumps(
339
+ {
340
+ "event": "E39_edit_complete",
341
+ "case": dest.name,
342
+ "E": timeline[-1]["E"]["accuracy"],
343
+ "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"],
344
+ }
345
+ ),
346
+ flush=True,
347
+ )
348
+
349
+
350
+ def run(args):
351
+ validate_study(json.loads(Path(args.config).read_text()))
352
+ parent, output = Path(args.parent).resolve(), Path(args.output).resolve()
353
+ if parent == output or parent in output.parents or output in parent.parents:
354
+ raise ValueError("E39 output must be separate from its immutable parent")
355
+ output.mkdir(parents=True, exist_ok=True)
356
+ with (output / ".lock").open("w") as lock:
357
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
358
+ torch.set_num_threads(args.threads)
359
+ config, checkpoint, predictions, low, high, world, provenance = load_parent(
360
+ parent, args.phase
361
+ )
362
+ pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)]
363
+ identity = {
364
+ "phase": args.phase,
365
+ "world": world.seed,
366
+ "seed": config["seed"],
367
+ "condition": config["condition"],
368
+ "study": STUDY,
369
+ "sources": editing_sources(),
370
+ "parent": provenance,
371
+ "data_contracts": [pair["contract"] for pair in pairs],
372
+ "torch": torch.__version__,
373
+ "cuda": torch.version.cuda,
374
+ "numpy": np.__version__,
375
+ "device_type": torch.device(args.device).type,
376
+ }
377
+ identity_path = output / "config.json"
378
+ if identity_path.exists() and json.loads(identity_path.read_text()) != identity:
379
+ raise ValueError("E39 editing identity or sources changed")
380
+ if not identity_path.exists():
381
+ write_json(identity_path, identity)
382
+ if (output / "complete.json").exists():
383
+ return
384
+ device = torch.device(args.device)
385
+ if device.type == "cuda":
386
+ torch.backends.cuda.matmul.allow_tf32 = True
387
+ torch.manual_seed(config["seed"])
388
+ if device.type == "cuda":
389
+ torch.cuda.manual_seed_all(config["seed"])
390
+ model = CausalLM(ModelConfig(**checkpoint["config"])).to(device)
391
+ model.load_state_dict(checkpoint["model"])
392
+ data = tensor_queries(world, device)
393
+ try:
394
+ baseline = {
395
+ key: value.detach().cpu().clone() for key, value in model.state_dict().items()
396
+ }
397
+ observed = evaluate(model, data, world.answers)
398
+ for key in ("prediction", "ended", "correct"):
399
+ np.testing.assert_array_equal(observed[key], predictions[key])
400
+ for chain in range(2):
401
+ for kind in KINDS:
402
+ run_case(
403
+ model,
404
+ baseline,
405
+ data,
406
+ world,
407
+ pairs[chain],
408
+ args.phase,
409
+ kind,
410
+ chain,
411
+ output,
412
+ file_hash(identity_path),
413
+ predictions,
414
+ device,
415
+ )
416
+ write_json(
417
+ output / "complete.json",
418
+ {
419
+ "status": "complete",
420
+ "phase": args.phase,
421
+ "edit_cases": 4,
422
+ "steps": 512,
423
+ "finished": time.time(),
424
+ },
425
+ )
426
+ except Exception as error:
427
+ write_json(
428
+ output / "failure.json",
429
+ {"type": type(error).__name__, "message": str(error), "time": time.time()},
430
+ )
431
+ raise
432
+
433
+
434
+ def main():
435
+ parser = argparse.ArgumentParser(description=__doc__)
436
+ parser.add_argument("--parent", required=True)
437
+ parser.add_argument("--phase", choices=PHASES, required=True)
438
+ parser.add_argument("--output", required=True)
439
+ parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json")
440
+ parser.add_argument("--device", default="cuda")
441
+ parser.add_argument("--threads", type=int, default=2)
442
+ run(parser.parse_args())
443
+
444
+
445
+ if __name__ == "__main__":
446
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepared E39 update sets shared by low/high shortcut-reliability worlds.
2
+
3
+ This file generates and audits data only. It neither trains nor edits a model.
4
+ The 96 proposed MLP edits are distinct from the archived E93 experiment.
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ from .bios_data import array_hash, rng_for
10
+ from .bios_shortcut_control import audit_high_exception
11
+
12
+ KINDS = ("coherent", "exception")
13
+ PHASES = ("low", "high")
14
+ BUDGET = {
15
+ "prevalence_levels": 2,
16
+ "worlds": 2,
17
+ "initializations": 2,
18
+ "organizations": 3,
19
+ "models": 24,
20
+ "chains": 2,
21
+ "update_types": 2,
22
+ "supports_per_chain": 1,
23
+ "scopes": ["mlp"],
24
+ "edit_cases": 96,
25
+ }
26
+ U_STRATA = {
27
+ "0": "original_exception_actual_in_affected_groups",
28
+ "1": "newly_exception_actual_in_affected_groups",
29
+ "2": "other_unchanged_facts_of_affected_people",
30
+ "3": "remaining_same_chain_facts",
31
+ "4": "remaining_cross_chain_or_independent_facts",
32
+ }
33
+
34
+
35
+ def make_matched_edit_pair(low, high, chain, support=0):
36
+ """Three roots + 36 actual facts; same IDs and support labels across phases.
37
+
38
+ Each selected group contributes six QA-trained and six QA-heldout people
39
+ who remain ordinary in the high-prevalence world. Coherent assigns all 12
40
+ to the new default. Exception assigns three default/three alternative in
41
+ each split. Histograms match ACROSS all three groups, not within a group.
42
+ """
43
+ if chain not in (0, 1) or support != 0:
44
+ raise ValueError("The prepared contract fixes two chains and support zero")
45
+ if low.seed != high.seed or low.n_base != high.n_base:
46
+ raise ValueError("Low/high worlds must share their identity and query layout")
47
+ audit_high_exception(low, high)
48
+ rng = rng_for(low.seed, 931, chain)
49
+ for _ in range(10000):
50
+ groups = rng.choice(64, 3, replace=False)
51
+ if len(np.unique(low.defaults[chain, groups])) == 3:
52
+ break
53
+ else:
54
+ raise RuntimeError("Could not find three groups with distinct default cities")
55
+ selected = np.empty((3, 12), dtype=np.int64)
56
+ conflict = np.zeros((3, 12), dtype=bool)
57
+ conflict[:, :3] = conflict[:, 6:9] = True
58
+ targets = {
59
+ f"{phase}_{kind}": world.answers.copy()
60
+ for phase, world in (("low", low), ("high", high))
61
+ for kind in KINDS
62
+ }
63
+ new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]]
64
+ alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]]
65
+ for index, group in enumerate(groups):
66
+ ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain])
67
+ for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])):
68
+ eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)]
69
+ if len(eligible) != 8:
70
+ raise ValueError("Expected eight still-ordinary people in each QA split")
71
+ selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6]
72
+ actual = low.actual_ids[chain, selected[index]]
73
+ derived = low.derived_ids[chain, low.memberships[chain] == group]
74
+ for phase in PHASES:
75
+ for kind in KINDS:
76
+ target = targets[f"{phase}_{kind}"]
77
+ target[low.root_ids[chain, group]] = new_default[index]
78
+ target[derived] = new_default[index]
79
+ target[actual] = new_default[index]
80
+ if kind == "exception":
81
+ target[actual[conflict[index]]] = alternative[index]
82
+ edited_people = selected.ravel()
83
+ selected_people = np.isin(low.memberships[chain], groups)
84
+ original = selected_people & low.exceptions[chain]
85
+ newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain]
86
+ unedited_ordinary = (
87
+ selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people)
88
+ )
89
+ e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]]))
90
+ d = low.derived_ids[chain, selected_people]
91
+ unchanged = np.ones(len(low.answers), dtype=bool)
92
+ unchanged[np.concatenate([e, d])] = False
93
+ affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)]
94
+ original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original])
95
+ newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly])
96
+ relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11])
97
+ strata = np.full(len(low.answers), -1, dtype=np.int64)
98
+ strata[unchanged & original_actual] = 0
99
+ strata[unchanged & newly_actual] = 1
100
+ strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2
101
+ strata[unchanged & ~affected_facts & relevant] = 3
102
+ strata[unchanged & ~affected_facts & ~relevant] = 4
103
+ heldout = []
104
+ for stratum in range(5):
105
+ ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10)))
106
+ heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))])
107
+ heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10)))
108
+ heldout = np.array(sorted(heldout), dtype=np.int64)
109
+ common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers))
110
+ common_pool = np.setdiff1d(common_pool, heldout)
111
+ if len(common_pool) < 4096:
112
+ raise ValueError("Insufficient shared unchanged base facts for R4096")
113
+ replay = rng.choice(common_pool, 4096, replace=False)
114
+ paired_reference = np.sort(low.derived_ids[chain, selected[conflict]])
115
+ pair = {
116
+ **targets,
117
+ "groups": groups,
118
+ "selected_people": selected,
119
+ "alternative_assignments": conflict,
120
+ "new_default": new_default,
121
+ "alternative": alternative,
122
+ "E": e,
123
+ "D": d,
124
+ "E_roots": low.root_ids[chain, groups],
125
+ "E_actual": np.sort(low.actual_ids[chain, edited_people]),
126
+ "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]),
127
+ "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]),
128
+ "D_trained": np.intersect1d(d, low.train_ids[chain]),
129
+ "D_heldout": np.intersect1d(d, low.heldout_ids[chain]),
130
+ "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]),
131
+ "paired_reference_D": paired_reference,
132
+ "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]),
133
+ "exception_conflict_D": paired_reference.copy(),
134
+ "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]),
135
+ "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]),
136
+ "D_original_exception": low.derived_ids[chain, original],
137
+ "D_newly_exception": low.derived_ids[chain, newly],
138
+ "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary],
139
+ "R": replay,
140
+ "U_full": np.flatnonzero(unchanged),
141
+ "U_heldout": heldout,
142
+ "U_strata": strata,
143
+ }
144
+ for phase in PHASES:
145
+ for kind in KINDS:
146
+ target = targets[f"{phase}_{kind}"]
147
+ actual_for_d = target[low.actual_ids[chain, selected_people]]
148
+ pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d]
149
+ pair["contract"] = {
150
+ "protocol": "v2.8-p3-shortcut-matched-E39-prepared",
151
+ "world": low.seed,
152
+ "chain": chain,
153
+ "support": support,
154
+ "status": "data_only_not_executed",
155
+ "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()},
156
+ "model_checkpoint": (
157
+ "width256, original 15360-step learning; not P2 30720-step continuation"
158
+ ),
159
+ "histogram_matching_scope": (
160
+ "all three groups combined; also separately for trained/heldout QA"
161
+ ),
162
+ "coherent_actuals_per_group": "12 new-default (six in each QA split)",
163
+ "exception_actuals_per_group": (
164
+ "6 new-default + 6 alternative (three + three in each QA split)"
165
+ ),
166
+ "paired_reference_semantics": (
167
+ "same 18 people; conflict only in exception, reference only in coherent"
168
+ ),
169
+ "R_semantics": (
170
+ "4096 identical query IDs with identical original truths "
171
+ "and unchanged under all four targets"
172
+ ),
173
+ "U_semantics": (
174
+ "common query IDs; score each phase against its own truth and old-correct coverage"
175
+ ),
176
+ "U_strata": U_STRATA.copy(),
177
+ "historical_E93_comparable": False,
178
+ "low_truth_sha256": array_hash(low.answers),
179
+ "high_truth_sha256": array_hash(high.answers),
180
+ "array_sha256": {key: array_hash(value) for key, value in pair.items()},
181
+ }
182
+ audit_matched_edit_pair(low, high, chain, pair)
183
+ return pair
184
+
185
+
186
+ def audit_matched_edit_pair(low, high, chain, pair):
187
+ """Verify ID, target, split, marginal, primary-subset, and replay contracts."""
188
+ audit_high_exception(low, high)
189
+ if low.seed != high.seed or low.n_base != high.n_base:
190
+ raise ValueError("Low/high world identities differ")
191
+ e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups"))
192
+ if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96:
193
+ raise ValueError("E39/D96 support changed")
194
+ if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3:
195
+ raise ValueError("Expected three groups with distinct original defaults")
196
+ if selected.shape != (3, 12) or len(np.unique(selected)) != 36:
197
+ raise ValueError("Expected twelve distinct people in each selected group")
198
+ if high.exceptions[chain, selected].any():
199
+ raise ValueError("Selected edit people must be ordinary in both worlds")
200
+ np.testing.assert_array_equal(
201
+ pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]]
202
+ )
203
+ np.testing.assert_array_equal(
204
+ pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]]
205
+ )
206
+ np.testing.assert_array_equal(
207
+ d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)]
208
+ )
209
+ np.testing.assert_array_equal(
210
+ e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]])
211
+ )
212
+ conflict = pair["alternative_assignments"]
213
+ if conflict.shape != (3, 12) or conflict.dtype != np.bool_:
214
+ raise ValueError("Invalid alternative assignment mask")
215
+ for index, group in enumerate(groups):
216
+ if not np.all(low.memberships[chain, selected[index]] == group):
217
+ raise ValueError("Selected person belongs to the wrong group")
218
+ for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])):
219
+ people = selected[index, split * 6 : (split + 1) * 6]
220
+ if not np.isin(low.derived_ids[chain, people], pool).all():
221
+ raise ValueError("Selected QA split changed")
222
+ if conflict[index, split * 6 : (split + 1) * 6].sum() != 3:
223
+ raise ValueError("Each group/split must have three default and three alternative")
224
+ root = low.root_ids[chain, group]
225
+ derived = low.derived_ids[chain, low.memberships[chain] == group]
226
+ actual = low.actual_ids[chain, selected[index]]
227
+ for phase in PHASES:
228
+ for kind in KINDS:
229
+ target = pair[f"{phase}_{kind}"]
230
+ if target[root] != pair["new_default"][index] or not np.all(
231
+ target[derived] == target[root]
232
+ ):
233
+ raise ValueError(
234
+ "The three root rotations and their full propagation targets must agree"
235
+ )
236
+ expected = np.full(12, target[root], dtype=np.int64)
237
+ if kind == "exception":
238
+ expected[conflict[index]] = pair["alternative"][index]
239
+ np.testing.assert_array_equal(target[actual], expected)
240
+ changed = np.union1d(e, d)
241
+ for phase, world in (("low", low), ("high", high)):
242
+ for kind in KINDS:
243
+ target = pair[f"{phase}_{kind}"]
244
+ np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed)
245
+ for kind in KINDS:
246
+ np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed])
247
+ for _split, pool in (
248
+ ("all", low.derived_ids[chain]),
249
+ ("trained", low.train_ids[chain]),
250
+ ("heldout", low.heldout_ids[chain]),
251
+ ):
252
+ people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)]
253
+ actual = low.actual_ids[chain, people]
254
+ np.testing.assert_array_equal(
255
+ np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual])
256
+ )
257
+ reference = np.sort(low.derived_ids[chain, selected[conflict]])
258
+ np.testing.assert_array_equal(pair["paired_reference_D"], reference)
259
+ np.testing.assert_array_equal(pair["exception_conflict_D"], reference)
260
+ heldout_reference = np.intersect1d(reference, low.heldout_ids[chain])
261
+ np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference)
262
+ np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference)
263
+ if len(reference) != 18 or len(heldout_reference) != 9:
264
+ raise ValueError("Expected eighteen primary exception conflicts, nine heldout")
265
+ partition = [
266
+ pair[key]
267
+ for key in (
268
+ "D_edited_actual",
269
+ "D_original_exception",
270
+ "D_newly_exception",
271
+ "D_remaining_ordinary_unedited",
272
+ )
273
+ ]
274
+ if [len(ids) for ids in partition] != [36, 6, 42, 12]:
275
+ raise ValueError("Incorrect fixed propagation strata")
276
+ np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d)
277
+ affected = np.isin(low.memberships[chain], groups)
278
+ expected_subsets = {
279
+ "E_roots": low.root_ids[chain, groups],
280
+ "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]),
281
+ "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]),
282
+ "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]),
283
+ "D_trained": np.intersect1d(d, low.train_ids[chain]),
284
+ "D_heldout": np.intersect1d(d, low.heldout_ids[chain]),
285
+ "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]),
286
+ "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]),
287
+ "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]],
288
+ "D_newly_exception": low.derived_ids[
289
+ chain, affected & high.exceptions[chain] & ~low.exceptions[chain]
290
+ ],
291
+ }
292
+ for key, expected in expected_subsets.items():
293
+ np.testing.assert_array_equal(pair[key], expected)
294
+ for phase in PHASES:
295
+ for kind in KINDS:
296
+ target = pair[f"{phase}_{kind}"]
297
+ conflicts = d[target[d] != target[low.actual_ids[chain, affected]]]
298
+ np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts)
299
+ u = np.setdiff1d(np.arange(len(low.answers)), changed)
300
+ np.testing.assert_array_equal(pair["U_full"], u)
301
+ np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u))
302
+ replay = pair["R"]
303
+ if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base):
304
+ raise ValueError("R must contain 4096 unique base-fact IDs")
305
+ if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size:
306
+ raise ValueError("Replay leaks changed support/propagation or heldout retention")
307
+ if not np.isin(pair["U_heldout"], u).all():
308
+ raise ValueError("Heldout retention includes changed targets")
309
+ np.testing.assert_array_equal(low.answers[replay], high.answers[replay])
310
+ for phase in PHASES:
311
+ for kind in KINDS:
312
+ np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay])
313
+ for key, value in pair.items():
314
+ if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash(
315
+ value
316
+ ):
317
+ raise ValueError(f"Matched update array provenance changed: {key}")
318
+ return {
319
+ "passed": True,
320
+ "E": 39,
321
+ "D": 96,
322
+ "exception_conflict_D": 18,
323
+ "exception_conflict_D_heldout": 9,
324
+ "R": 4096,
325
+ "budget_edit_cases": 96,
326
+ "histograms_match_across_three_groups_and_within_QA_split": True,
327
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_train.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproducible symbolic development trajectories for bioS-Work-v1.
2
+
3
+ Every evaluated answer is greedily generated without a correct-answer prefix.
4
+ Two generated tokens is the fixed symbolic grammar budget (one value plus EOS).
5
+ """
6
+
7
+ import argparse
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import platform
12
+ import subprocess
13
+ import time
14
+ from contextlib import nullcontext
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch.nn import functional as F
20
+
21
+ from .bios_data import (
22
+ EOS,
23
+ N_BASE,
24
+ N_QUERIES,
25
+ RELATIONS,
26
+ array_hash,
27
+ curriculum,
28
+ load_world,
29
+ write_json,
30
+ )
31
+ from .bios_model import CausalLM, ModelConfig, matmul_flops
32
+
33
+
34
+ def precision(device):
35
+ return (
36
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16)
37
+ if device.type == "cuda"
38
+ else nullcontext()
39
+ )
40
+
41
+
42
+ def tensor_data(world, device, answers=None):
43
+ answer = torch.as_tensor(world.answers if answers is None else answers, device=device)
44
+ prompts = torch.as_tensor(world.prompts, device=device)
45
+ lengths = torch.as_tensor(world.lengths, device=device)
46
+ tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device)
47
+ tokens[:, :5] = prompts
48
+ rows = torch.arange(N_QUERIES, device=device)
49
+ tokens[rows, lengths] = answer
50
+ tokens[lengths == 4, 5] = EOS
51
+ positions = torch.stack([lengths - 1, lengths], dim=1)
52
+ labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1)
53
+ return {
54
+ "prompts": prompts,
55
+ "lengths": lengths,
56
+ "tokens": tokens,
57
+ "positions": positions,
58
+ "labels": labels,
59
+ }
60
+
61
+
62
+ @torch.no_grad()
63
+ def evaluate(model, data, world, batch_size=512, answers=None):
64
+ device = data["tokens"].device
65
+ targets = world.answers if answers is None else answers
66
+ predictions, ended, nll = [], [], []
67
+ model.eval()
68
+ for begin in range(0, N_QUERIES, batch_size):
69
+ end = min(begin + batch_size, N_QUERIES)
70
+ lengths = data["lengths"][begin:end]
71
+ rows = torch.arange(end - begin, device=device)
72
+ with precision(device):
73
+ logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float()
74
+ first = logits.argmax(-1)
75
+ continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device)
76
+ continuation[:, :5] = data["prompts"][begin:end]
77
+ continuation[rows, lengths] = first
78
+ second = model(continuation, lengths[:, None])[:, 0].argmax(-1)
79
+ predictions.append(first.cpu().numpy())
80
+ ended.append(second.eq(EOS).cpu().numpy())
81
+ labels = torch.as_tensor(targets[begin:end], device=device)
82
+ nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy())
83
+ predictions, ended, nll = (
84
+ np.concatenate(predictions),
85
+ np.concatenate(ended),
86
+ np.concatenate(nll),
87
+ )
88
+ correct = (predictions == targets) & ended
89
+ strata = {
90
+ "employer": world.relation == 0,
91
+ "company_default": world.relation == 1,
92
+ "actual_nonexception": (world.relation == 2)
93
+ & ~world.exceptions[np.maximum(world.person, 0)],
94
+ "actual_old_exception": (world.relation == 2)
95
+ & world.exceptions[np.maximum(world.person, 0)],
96
+ "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]),
97
+ }
98
+ metrics = {
99
+ "base_accuracy": float(correct[:N_BASE].mean()),
100
+ "derived_accuracy": float(correct[N_BASE:].mean()),
101
+ "value_nll": float(nll[:N_BASE].mean()),
102
+ "nontermination_rate": float((~ended).mean()),
103
+ "strata": {k: float(correct[v].mean()) for k, v in strata.items()},
104
+ "learning_threshold_passed": bool(
105
+ correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99
106
+ ),
107
+ }
108
+ return metrics, {
109
+ "prediction": predictions,
110
+ "ended": ended,
111
+ "correct": correct,
112
+ "value_nll": nll,
113
+ }
114
+
115
+
116
+ def code_fingerprint():
117
+ root = Path(__file__).resolve().parents[2]
118
+ files = sorted((root / "src" / "llm_memory_editability").glob("*.py"))
119
+ return {
120
+ "git_revision": subprocess.check_output(
121
+ ["git", "rev-parse", "HEAD"], cwd=root, text=True
122
+ ).strip(),
123
+ "git_dirty": bool(
124
+ subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip()
125
+ ),
126
+ "source_sha256": {
127
+ str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
128
+ },
129
+ }
130
+
131
+
132
+ def train(args):
133
+ device = torch.device(args.device)
134
+ torch.set_num_threads(args.threads)
135
+ torch.manual_seed(args.seed)
136
+ if device.type == "cuda":
137
+ torch.cuda.manual_seed_all(args.seed)
138
+ torch.backends.cuda.matmul.allow_tf32 = True
139
+ world = load_world(args.world)
140
+ out = Path(args.output)
141
+ out.mkdir(parents=True, exist_ok=True)
142
+ resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None
143
+ if resume is None and (out / "config.json").exists():
144
+ raise ValueError("Output already contains a run; use a fresh output directory")
145
+ schedule = curriculum(world, args.order, args.steps)
146
+ model = CausalLM(ModelConfig(world.vocab_size)).to(device)
147
+ data = tensor_data(world, device)
148
+ optimizer = torch.optim.AdamW(
149
+ model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda"
150
+ )
151
+ checkpoints = sorted(
152
+ {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps}
153
+ )
154
+ config = {
155
+ **vars(args),
156
+ "model": model.config_dict(),
157
+ "protocol": "v2.3",
158
+ "phase": "development",
159
+ "world_seed": world.seed,
160
+ "parameters": sum(p.numel() for p in model.parameters()),
161
+ "torch": torch.__version__,
162
+ "python": platform.python_version(),
163
+ "numpy": np.__version__,
164
+ "cuda": torch.version.cuda,
165
+ "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
166
+ "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
167
+ "precision": "BF16 autocast, FP32 weights/loss/Adam moments",
168
+ "checkpoints": checkpoints,
169
+ "schedule_sha256": array_hash(schedule),
170
+ "truth_sha256": array_hash(world.answers),
171
+ "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded",
172
+ **code_fingerprint(),
173
+ }
174
+ timeline, anchors = [], {}
175
+ counts = np.zeros(N_QUERIES, dtype=np.int64)
176
+ weighted_exposure = np.zeros(8)
177
+ train_seconds = 0.0
178
+ losses = []
179
+ steps_since_checkpoint = 0
180
+ first_step = 0
181
+ if resume is None:
182
+ write_json(out / "config.json", config)
183
+ np.save(out / "schedule.npy", schedule)
184
+ else:
185
+ # Exact continuation from the last predefined checkpoint's full training state.
186
+ original = json.loads((out / "config.json").read_text())
187
+ for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"):
188
+ if original[key] != config[key]:
189
+ raise ValueError(f"Resume mismatch on {key}")
190
+ model.load_state_dict(resume["model"])
191
+ optimizer.load_state_dict(resume["optimizer"])
192
+ torch.set_rng_state(resume["torch_rng"])
193
+ if device.type == "cuda" and resume["cuda_rng"] is not None:
194
+ torch.cuda.set_rng_state(resume["cuda_rng"], device)
195
+ timeline, anchors = resume["timeline"], resume["anchors"]
196
+ counts, weighted_exposure = resume["counts"], resume["weighted_exposure"]
197
+ train_seconds = resume["train_seconds"]
198
+ first_step = resume["step"]
199
+ resumes = (
200
+ json.loads((out / "resumes.json").read_text())
201
+ if (out / "resumes.json").exists()
202
+ else []
203
+ )
204
+ resumes.append({"from_step": first_step, **code_fingerprint()})
205
+ write_json(out / "resumes.json", resumes)
206
+ if device.type == "cuda":
207
+ torch.cuda.reset_peak_memory_stats(device)
208
+ for step in range(first_step, args.steps + 1):
209
+ if step in checkpoints and not (resume is not None and step == first_step):
210
+ start_eval = time.perf_counter()
211
+ metrics, arrays = evaluate(model, data, world)
212
+ for anchor, known in anchors.items():
213
+ metrics[f"forgetting_since_{anchor}"] = (
214
+ float((~arrays["correct"][known]).mean()) if known.any() else None
215
+ )
216
+ if step in (2640, 5280):
217
+ anchors[step] = arrays["correct"].copy()
218
+ np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts)
219
+ # CPU state for portability; all predefined checkpoints retained.
220
+ torch.save(
221
+ {
222
+ "model": {k: v.detach().cpu() for k, v in model.state_dict().items()},
223
+ "config": model.config_dict(),
224
+ "step": step,
225
+ },
226
+ out / f"model-{step}.pt",
227
+ )
228
+ record = {
229
+ "step": step,
230
+ **metrics,
231
+ "train_seconds": train_seconds,
232
+ "train_matmul_flops_estimate": step * matmul_flops(model.config, 128),
233
+ "presentations": int(counts.sum()),
234
+ "coverage_base": float((counts[:N_BASE] > 0).mean()),
235
+ "coverage_derived": float((counts[N_BASE:] > 0).mean()),
236
+ "world_tokens": int((counts * (world.lengths + 2)).sum()),
237
+ "input_tokens_including_padding": step * 128 * 6,
238
+ "supervised_tokens": step * 128 * 2,
239
+ "lr_weighted_exposure_by_relation": dict(
240
+ zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True)
241
+ ),
242
+ "peak_cuda_bytes": torch.cuda.max_memory_allocated(device)
243
+ if device.type == "cuda"
244
+ else 0,
245
+ "eval_and_checkpoint_seconds": time.perf_counter() - start_eval,
246
+ "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None,
247
+ }
248
+ timeline.append(record)
249
+ write_json(out / "learning.json", timeline)
250
+ print(
251
+ json.dumps(
252
+ {
253
+ "event": "checkpoint",
254
+ "step": step,
255
+ "base": metrics["base_accuracy"],
256
+ "derived": metrics["derived_accuracy"],
257
+ "train_seconds": train_seconds,
258
+ }
259
+ ),
260
+ flush=True,
261
+ )
262
+ losses = []
263
+ steps_since_checkpoint = 0
264
+ state = {
265
+ "model": model.state_dict(),
266
+ "optimizer": optimizer.state_dict(),
267
+ "torch_rng": torch.get_rng_state(),
268
+ "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None,
269
+ "timeline": timeline,
270
+ "anchors": anchors,
271
+ "counts": counts,
272
+ "weighted_exposure": weighted_exposure,
273
+ "train_seconds": train_seconds,
274
+ "step": step,
275
+ }
276
+ torch.save(state, out / "resume.pt.tmp")
277
+ os.replace(out / "resume.pt.tmp", out / "resume.pt")
278
+ if step == args.steps:
279
+ break
280
+ model.train()
281
+ lr = args.lr * min((step + 1) / 2000, 1.0)
282
+ for group in optimizer.param_groups:
283
+ group["lr"] = lr
284
+ ids_np = schedule[step]
285
+ ids = torch.as_tensor(ids_np, device=device)
286
+ if device.type == "cuda":
287
+ torch.cuda.synchronize(device)
288
+ started = time.perf_counter()
289
+ optimizer.zero_grad(set_to_none=True)
290
+ with precision(device):
291
+ logits = model(data["tokens"][ids], data["positions"][ids])
292
+ loss = F.cross_entropy(
293
+ logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1)
294
+ )
295
+ loss.backward()
296
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
297
+ if not torch.isfinite(loss) or not torch.isfinite(norm):
298
+ write_json(
299
+ out / "failure.json",
300
+ {
301
+ "step": step,
302
+ "reason": "nonfinite loss or gradient",
303
+ "train_seconds": train_seconds,
304
+ },
305
+ )
306
+ raise FloatingPointError("Nonfinite loss or gradient")
307
+ optimizer.step()
308
+ if device.type == "cuda":
309
+ torch.cuda.synchronize(device)
310
+ train_seconds += time.perf_counter() - started
311
+ losses.append(loss.item())
312
+ np.add.at(counts, ids_np, 1)
313
+ weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr
314
+ steps_since_checkpoint += 1
315
+ if (step + 1) % 100 == 0:
316
+ print(
317
+ json.dumps(
318
+ {
319
+ "event": "progress",
320
+ "step": step + 1,
321
+ "loss": float(np.mean(losses[-100:])),
322
+ "train_seconds": train_seconds,
323
+ }
324
+ ),
325
+ flush=True,
326
+ )
327
+ write_json(
328
+ out / "complete.json",
329
+ {
330
+ "step": args.steps,
331
+ "status": "complete",
332
+ "final": timeline[-1],
333
+ "exposure_sha256": array_hash(counts),
334
+ },
335
+ )
336
+
337
+
338
+ def main():
339
+ parser = argparse.ArgumentParser(description=__doc__)
340
+ parser.add_argument("--world", required=True)
341
+ parser.add_argument("--output", required=True)
342
+ parser.add_argument("--order", choices=["SA", "AS"], required=True)
343
+ parser.add_argument("--seed", type=int, default=0)
344
+ parser.add_argument("--steps", type=int, default=13280)
345
+ parser.add_argument("--lr", type=float, default=1e-4)
346
+ parser.add_argument("--device", default="cuda")
347
+ parser.add_argument("--threads", type=int, default=4)
348
+ parser.add_argument("--resume", action="store_true")
349
+ train(parser.parse_args())
350
+
351
+
352
+ if __name__ == "__main__":
353
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_reencoding.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-weight, self-decoded bridge re-encoding in existing small GPTs.
2
+
3
+ The intervention uses the original tied readout over the complete vocabulary.
4
+ Only the explicitly named oracle condition accesses graph answers at inference.
5
+ The wrong_entity control is an alternative to the model's decoded token, not a
6
+ guaranteed incorrect answer: its accidental agreement with truth is reported.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torch.nn import functional as F
19
+
20
+ from .grok_depth import utc, write_json
21
+ from .latent_scaling import build_world, model_digest
22
+ from .representation_alignment import RepresentationGPT, new_model
23
+ from .storage_composition import data_digest, evaluate, file_hash, generate_rows
24
+ from .text_pretrain import WORDS, composite_sentence
25
+
26
+ CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle")
27
+
28
+
29
+ def reencode_state(state, embedding, alpha, variant="norm_matched"):
30
+ """Interpolate residual and normalized embedding, without renormalizing the sum.
31
+
32
+ norm_matched gives the replacement embedding the original state's norm.
33
+ paper_unit uses a unit embedding directly. Neither preserves the mixture's
34
+ norm in general; alpha=0 returns the original tensor exactly.
35
+ """
36
+ if not 0 <= alpha <= 1:
37
+ raise ValueError("alpha must be between zero and one")
38
+ if variant not in ("norm_matched", "paper_unit"):
39
+ raise ValueError("Unknown re-encoding variant")
40
+ if alpha == 0:
41
+ return state
42
+ replacement = F.normalize(embedding, dim=-1)
43
+ if variant == "norm_matched":
44
+ replacement = state.norm(dim=-1, keepdim=True) * replacement
45
+ return (1 - alpha) * state + alpha * replacement
46
+
47
+
48
+ def alternative_entity(decoded, bridge_start, bridge_count):
49
+ """A non-self bridge-entity choice, independent of the true bridge identity."""
50
+ if bridge_count < 2:
51
+ raise ValueError("At least two bridge entity tokens are required")
52
+ return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count)
53
+
54
+
55
+ class ReencodingGPT(RepresentationGPT):
56
+ """Original computation with a single intervention at block 0, position 3."""
57
+
58
+ def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"):
59
+ if condition not in CONDITIONS:
60
+ raise ValueError(f"Unknown condition: {condition}")
61
+ if not 0 <= alpha <= 1:
62
+ raise ValueError("alpha must be between zero and one")
63
+ if variant not in ("norm_matched", "paper_unit"):
64
+ raise ValueError("Unknown re-encoding variant")
65
+ if condition == "oracle" and oracle_table is None:
66
+ raise ValueError("Oracle condition requires an explicit diagnostic truth table")
67
+ self.condition, self.alpha, self.variant = condition, float(alpha), variant
68
+ # Deliberately outside state_dict: neither weights nor model hashes change.
69
+ self.oracle_table = oracle_table if condition == "oracle" else None
70
+
71
+ def _choice(self, state, tokens):
72
+ decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1)
73
+ selected = decoded
74
+ oracle_available = torch.zeros_like(decoded, dtype=torch.bool)
75
+ if self.condition == "wrong_entity":
76
+ selected = alternative_entity(decoded, self.bridge_start, self.bridge_count)
77
+ elif self.condition == "oracle":
78
+ oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]]
79
+ oracle_available = oracle >= 0
80
+ # Invalid autonomously generated heads have no graph truth. Do not
81
+ # fabricate an oracle answer; retain the model's decoded token.
82
+ selected = torch.where(oracle_available, oracle, decoded)
83
+ return decoded, selected, oracle_available
84
+
85
+ def forward(self, tokens, positions=None, repeats=None, return_bridge=False):
86
+ if not return_bridge and (self.condition == "baseline" or self.alpha == 0):
87
+ return super().forward(tokens, positions=positions, repeats=repeats)
88
+ if tokens.shape[1] < 4:
89
+ raise ValueError("The intervention requires the causal first-relation prefix")
90
+ p = self.dropout if self.training else 0.0
91
+ x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
92
+ x = F.dropout(x, p=p, training=self.training)
93
+ info = None
94
+ for index, block in enumerate(self.iter_blocks(repeats)):
95
+ z = block.ln1(x)
96
+ batch, length, width = z.shape
97
+ a = block.attention
98
+ q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
99
+ y = F.scaled_dot_product_attention(
100
+ q.transpose(1, 2),
101
+ k.transpose(1, 2),
102
+ v.transpose(1, 2),
103
+ is_causal=True,
104
+ dropout_p=p,
105
+ )
106
+ y = a.proj(y.transpose(1, 2).reshape(batch, length, width))
107
+ x = x + F.dropout(y, p=p, training=self.training)
108
+ x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training)
109
+ if index == 0:
110
+ state = x[:, 3]
111
+ decoded, selected, oracle_available = self._choice(state, tokens)
112
+ replacement = (
113
+ state
114
+ if self.condition == "baseline"
115
+ else reencode_state(state, self.token(selected), self.alpha, self.variant)
116
+ )
117
+ if self.condition != "baseline" and self.alpha:
118
+ x = x.clone()
119
+ x[:, 3] = replacement
120
+ info = {
121
+ "state": state,
122
+ "replacement": replacement,
123
+ "decoded": decoded,
124
+ "selected": selected,
125
+ "oracle_available": oracle_available,
126
+ }
127
+ x = self.ln_final(x)
128
+ if positions is not None:
129
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
130
+ logits = F.linear(x, self.token.weight)
131
+ return (logits, info) if return_bridge else logits
132
+
133
+
134
+ def _device_settings(device):
135
+ device = torch.device(device)
136
+ torch.set_num_threads(1)
137
+ torch.backends.cuda.matmul.allow_tf32 = True
138
+ torch.backends.cudnn.allow_tf32 = True
139
+ if device.type == "cuda":
140
+ torch.cuda.set_device(device)
141
+ return device
142
+
143
+
144
+ def _load(spec, device):
145
+ parent = Path(spec["parent_dir"]).resolve()
146
+ checkpoint = parent / "model.pt"
147
+ payload = torch.load(checkpoint, map_location="cpu", weights_only=False)
148
+ model = new_model(payload["spec"], device)
149
+ model.load_state_dict(payload["model"])
150
+ model.__class__ = ReencodingGPT
151
+ model.bridge_start = len(WORDS) + payload["spec"]["heads_n"]
152
+ model.bridge_count = payload["spec"]["bridges_n"]
153
+ model.configure("baseline", 0)
154
+ model.eval().requires_grad_(False)
155
+ world = dict(np.load(parent / "world.npz"))
156
+ rebuilt = build_world(payload["spec"])
157
+ if data_digest(world) != data_digest(rebuilt):
158
+ raise AssertionError("Saved world differs from the parent specification")
159
+ oracle = torch.full(
160
+ (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long
161
+ )
162
+ for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])):
163
+ oracle[h, r] = int(target)
164
+ return model, world, oracle, payload["spec"], checkpoint
165
+
166
+
167
+ @torch.no_grad()
168
+ def _diagnostics(model, rows, device, batch_size):
169
+ prompts = np.asarray([composite_sentence(row)[:7] for row in rows])
170
+ collected = {}
171
+ model.eval()
172
+ for start in range(0, len(rows), batch_size):
173
+ tokens = torch.as_tensor(prompts[start : start + batch_size], device=device)
174
+ _, info = model(tokens, return_bridge=True)
175
+ values = {
176
+ "decoded_bridge": info["decoded"],
177
+ "selected_bridge": info["selected"],
178
+ "oracle_available": info["oracle_available"],
179
+ "state_norm": info["state"].norm(dim=-1),
180
+ "replacement_norm": info["replacement"].norm(dim=-1),
181
+ }
182
+ for key, value in values.items():
183
+ collected.setdefault(key, []).append(value.cpu().numpy())
184
+ result = {key: np.concatenate(value) for key, value in collected.items()}
185
+ result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2]
186
+ result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2]
187
+ result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS)
188
+ return result
189
+
190
+
191
+ def _subset_metric(correct, mask):
192
+ return {
193
+ "n": int(mask.sum()),
194
+ "coverage": float(mask.mean()),
195
+ "accuracy": float(correct[mask].mean()) if mask.any() else None,
196
+ }
197
+
198
+
199
+ @torch.no_grad()
200
+ def _evaluate_condition(model, world, device, batch_size):
201
+ # Reuse the established complete answer/period/EOS scorer unchanged. Its
202
+ # canonical batch is 512; diagnostics use the same shapes for exact decoding.
203
+ if batch_size != 512:
204
+ raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic")
205
+ metrics, predictions = evaluate(model, world, "low", device)
206
+ model.eval()
207
+ for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"):
208
+ generated = predictions[name + "_generated"]
209
+ metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean())
210
+ metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean())
211
+ metrics[name]["format_accuracy"] = float(
212
+ ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean()
213
+ )
214
+ for name in ("familiar_test", "strict_test"):
215
+ rows = world[name]
216
+ info = _diagnostics(model, rows, device, batch_size)
217
+ predictions.update({name + "_" + key: value for key, value in info.items()})
218
+ for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"):
219
+ metrics[name][key + "_coverage"] = float(info[key].mean())
220
+ if model.condition == "wrong_entity":
221
+ metrics[name]["alternative_accidental_gold_match"] = float(
222
+ info["selected_bridge_correct"].mean()
223
+ )
224
+ correct = predictions[name + "_correct"]
225
+ metrics[name]["self_bridge_correct_subset"] = _subset_metric(
226
+ correct, info["decoded_bridge_correct"]
227
+ )
228
+ first = rows[:, [0, 1, 2]]
229
+ second = rows[:, [2, 3, 4]]
230
+ for role, atoms in (("first", first), ("second", second)):
231
+ _, raw = generate_rows(model, atoms, device, batch_size=batch_size)
232
+ predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()})
233
+ autonomous_second = second.copy()
234
+ autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0]
235
+ _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size)
236
+ predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()})
237
+ return metrics, predictions
238
+
239
+
240
+ def cases(spec):
241
+ """One baseline and the frozen alpha/variant/condition matrix."""
242
+ conditions = list(spec.get("conditions", CONDITIONS))
243
+ if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions):
244
+ raise ValueError("Conditions must be distinct known names")
245
+ alphas = spec.get("alphas", [spec.get("alpha", 0)])
246
+ variants = spec.get("variants", ["norm_matched"])
247
+ if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas):
248
+ raise ValueError("alphas must contain distinct values in [0,1]")
249
+ if len(variants) != len(set(variants)) or not variants:
250
+ raise ValueError("variants must be distinct and nonempty")
251
+ if any(v not in ("norm_matched", "paper_unit") for v in variants):
252
+ raise ValueError("Unknown re-encoding variant")
253
+ matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}}
254
+ for variant in variants:
255
+ for alpha in alphas:
256
+ for condition in conditions:
257
+ if condition == "baseline":
258
+ continue
259
+ name = f"{variant}-a{float(alpha):g}-{condition}"
260
+ matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant}
261
+ return matrix
262
+
263
+
264
+ def _evaluate_all(model, world, oracle, spec, callback=None):
265
+ matrix = cases(spec)
266
+ metrics, arrays = {}, {}
267
+ for name, case in matrix.items():
268
+ model.configure(
269
+ case["condition"],
270
+ case["alpha"],
271
+ oracle if case["condition"] == "oracle" else None,
272
+ case["variant"],
273
+ )
274
+ metrics[name], predictions = _evaluate_condition(
275
+ model, world, next(model.parameters()).device, spec.get("batch_size", 512)
276
+ )
277
+ arrays.update({name + "__" + key: value for key, value in predictions.items()})
278
+ if callback is not None:
279
+ callback(name, case, metrics[name], predictions)
280
+ for name in ("familiar_test", "strict_test"):
281
+ baseline = arrays[f"baseline__{name}_coverage"]
282
+ # This is the fixed pre-intervention prerequisite pool for every case.
283
+ # In particular, the destructive alternative-entity control cannot
284
+ # determine which chains enter the main conditional comparison.
285
+ arrays[f"common__{name}_atomic_correct"] = baseline
286
+ for condition in matrix:
287
+ correct = arrays[f"{condition}__{name}_correct"]
288
+ arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline
289
+ metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric(
290
+ correct, baseline
291
+ )
292
+ self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"]
293
+ joint = baseline & self_ok
294
+ arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint
295
+ metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric(
296
+ correct, joint
297
+ )
298
+ model.configure("baseline", 0)
299
+ return metrics, arrays
300
+
301
+
302
+ def run(spec, out, device="cuda:2"):
303
+ """Evaluate one existing checkpoint; never train or overwrite an attempt."""
304
+ out = Path(out)
305
+ if (out / "run.json").exists():
306
+ raise FileExistsError(f"Do not overwrite an attempt: {out}")
307
+ out.mkdir(parents=True, exist_ok=True)
308
+ device = _device_settings(device)
309
+ started = time.perf_counter()
310
+ model, world, oracle, parent_spec, checkpoint = _load(spec, device)
311
+ digest = model_digest(model)
312
+ source = {
313
+ str(Path(__file__).resolve()): file_hash(__file__),
314
+ "parent_checkpoint": file_hash(checkpoint),
315
+ }
316
+ manifest = {
317
+ "spec": spec,
318
+ "parent_spec": parent_spec,
319
+ "source": source,
320
+ "world_sha256": data_digest(world),
321
+ "model_sha256": digest,
322
+ "pid": os.getpid(),
323
+ "device": str(device),
324
+ "started_utc": utc(),
325
+ "new_training_updates": 0,
326
+ "optimizer_updates": 0,
327
+ "cases": cases(spec),
328
+ "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)",
329
+ "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)",
330
+ "decoder": "original ln_final and tied output, argmax over the full vocabulary",
331
+ "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge",
332
+ "bridge_token_start": model.bridge_start,
333
+ "bridge_token_count": model.bridge_count,
334
+ "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline",
335
+ "alpha_zero_exact_bypass": True,
336
+ "allow_tf32": True,
337
+ }
338
+ write_json(out / "run.json", manifest)
339
+ np.savez_compressed(out / "world.npz", **world)
340
+ history = []
341
+
342
+ def record(name, case, metrics, predictions):
343
+ history.append(
344
+ {
345
+ "step": len(history) + 1,
346
+ "case": name,
347
+ **case,
348
+ "metrics": metrics,
349
+ "optimizer_updates": 0,
350
+ "wall_seconds": time.perf_counter() - started,
351
+ "created_utc": utc(),
352
+ }
353
+ )
354
+ # Each condition is durable before the next one starts.
355
+ np.savez_compressed(out / f"predictions-{name}.npz", **predictions)
356
+ write_json(out / "learning.json", history)
357
+ write_json(
358
+ out / "status.json",
359
+ {
360
+ "state": "running",
361
+ "step": len(history),
362
+ "budget": len(manifest["cases"]),
363
+ "optimizer_updates": 0,
364
+ },
365
+ )
366
+
367
+ metrics, predictions = _evaluate_all(model, world, oracle, spec, record)
368
+ assert model_digest(model) == digest, "Evaluation changed model parameters"
369
+ # Final common-prerequisite subsets are known only after the full matrix.
370
+ write_json(out / "learning.json", history)
371
+ # At zero weight all conditions must recover complete baseline generation.
372
+ for key, value in predictions.items():
373
+ if key.endswith(("_generated", "_answer_nll")):
374
+ case, suffix = key.split("__", 1)
375
+ if manifest["cases"][case]["alpha"] == 0:
376
+ np.testing.assert_array_equal(value, predictions["baseline__" + suffix])
377
+ np.savez_compressed(out / "predictions.npz", **predictions)
378
+ write_json(out / "metrics.json", metrics)
379
+ result = {
380
+ "state": "evaluation-complete-awaiting-independent-audit",
381
+ "finished_utc": utc(),
382
+ "wall_seconds": time.perf_counter() - started,
383
+ "model_sha256": digest,
384
+ "new_training_updates": 0,
385
+ "optimizer_updates": 0,
386
+ "conditions": list(metrics),
387
+ "prediction_arrays": len(predictions),
388
+ "step": len(history),
389
+ }
390
+ write_json(out / "evaluation-complete.json", result)
391
+ write_json(out / "status.json", {**result, "step": len(history)})
392
+ return result
393
+
394
+
395
+ def audit(out, device="cuda:2"):
396
+ """Reload weights and independently recompute every saved prediction array."""
397
+ out = Path(out)
398
+ device = _device_settings(device)
399
+ manifest = json.loads((out / "run.json").read_text())
400
+ model, world, oracle, _, checkpoint = _load(manifest["spec"], device)
401
+ assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"]
402
+ assert model_digest(model) == manifest["model_sha256"]
403
+ assert data_digest(world) == manifest["world_sha256"]
404
+ metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"])
405
+ saved = dict(np.load(out / "predictions.npz"))
406
+ assert set(saved) == set(actual), "Prediction array set changed"
407
+ max_error = 0.0
408
+ for key, value in actual.items():
409
+ if value.dtype.kind == "f":
410
+ max_error = max(max_error, float(np.max(np.abs(value - saved[key]))))
411
+ np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5)
412
+ else:
413
+ np.testing.assert_array_equal(value, saved[key])
414
+ # Recount complete-answer accuracy independently of the established scorer.
415
+ for condition, groups in metrics.items():
416
+ for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"):
417
+ pred = actual[f"{condition}__{name}_generated"]
418
+ correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1)
419
+ np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"])
420
+ assert float(correct.mean()) == groups[name]["accuracy"]
421
+ assert model_digest(model) == manifest["model_sha256"]
422
+ result = {
423
+ "passed": True,
424
+ "independently_reloaded": True,
425
+ "raw_predictions_recounted": True,
426
+ "prediction_arrays": len(actual),
427
+ "max_float_error": max_error,
428
+ "audit_pid": os.getpid(),
429
+ "independent_process": os.getpid() != manifest["pid"],
430
+ "finished_utc": utc(),
431
+ "metrics": metrics,
432
+ }
433
+ write_json(out / "audit.json", result)
434
+ complete = json.loads((out / "evaluation-complete.json").read_text())
435
+ complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc())
436
+ write_json(out / "complete.json", complete)
437
+ write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0})
438
+ return result
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_workspace.py ADDED
@@ -0,0 +1,1112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal entity-coordinate interventions using an averaged prefix Jacobian.
2
+
3
+ This is a restricted adaptation of Anthropic's Jacobian lens: calibration and
4
+ donors contain only the first fact's query prefix. No relation suffix or answer
5
+ gradient is used to construct a direction. Execution layers count shared block
6
+ occurrences separately. All model parameters remain frozen.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import time
15
+ from collections import defaultdict
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch.nn import functional as F
21
+
22
+ from .grok_depth import utc, write_json
23
+ from .latent_scaling import model_digest
24
+ from .storage_composition import file_hash
25
+
26
+ SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back")
27
+ ERASURES = (
28
+ "erase_state",
29
+ "erase_mlp",
30
+ "erase_attention",
31
+ "random_state",
32
+ "random_mlp",
33
+ "random_attention",
34
+ "restore_mlp",
35
+ "fixed_entity_mlp",
36
+ "fixed_entity_random_mlp",
37
+ )
38
+
39
+
40
+ class ModelView:
41
+ """Expose native attention/MLP increments without replacing trained modules."""
42
+
43
+ def __init__(self, model):
44
+ if model.training:
45
+ raise ValueError("Interventions require eval mode")
46
+ self.model = model
47
+ self.large = hasattr(model, "transformer")
48
+ if self.large:
49
+ t = model.transformer
50
+ self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f
51
+ self.blocks = list(t.h) * model.repeats
52
+ self.heads = model.config.n_head
53
+ else:
54
+ self.embedding, self.position, self.norm = model.token, model.position, model.ln_final
55
+ self.blocks = list(model.iter_blocks())
56
+ self.heads = model.config.heads
57
+ self.width = self.embedding.weight.shape[1]
58
+ self.device = self.embedding.weight.device
59
+
60
+ def embed(self, tokens):
61
+ return self.embedding(tokens) + self.position(
62
+ torch.arange(tokens.shape[1], device=self.device)
63
+ )
64
+
65
+ def parts(self, x, block, *, math_attention=False):
66
+ if self.large:
67
+ z = block.ln_1(x)
68
+ q, k, v = block.attn.c_attn(z).split(self.width, dim=-1)
69
+ project, ln2 = block.attn.c_proj, block.ln_2
70
+ else:
71
+ z = block.ln1(x)
72
+ q, k, v = block.attention.qkv(z).chunk(3, dim=-1)
73
+ project, ln2 = block.attention.proj, block.ln2
74
+ shape = (len(x), x.shape[1], self.heads, self.width // self.heads)
75
+ q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v))
76
+ if math_attention:
77
+ # The explicit FP32 expression permits batched VJPs on torch 2.6.
78
+ scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5
79
+ mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril()
80
+ y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v
81
+ else:
82
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
83
+ attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width))
84
+ after_attention = x + attention
85
+ mlp = block.mlp(ln2(after_attention))
86
+ return after_attention + mlp, attention, mlp
87
+
88
+ def hidden(
89
+ self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False
90
+ ):
91
+ x, states, attentions, mlps = self.embed(tokens), [], [], []
92
+ for index, block in enumerate(self.blocks):
93
+ x, attention, mlp = self.parts(x, block, math_attention=math_attention)
94
+ if capture:
95
+ states.append(x[:, sender].detach())
96
+ attentions.append(attention[:, sender].detach())
97
+ mlps.append(mlp[:, sender].detach())
98
+ if index == layer:
99
+ if sender is None or delta is None or delta.shape != x[:, sender].shape:
100
+ raise ValueError("A patch requires one delta per example at a fixed sender")
101
+ mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype)
102
+ x = x + mask[None, :, None] * delta[:, None, :]
103
+ if capture:
104
+ return x, tuple(torch.stack(a) for a in (states, attentions, mlps))
105
+ return x
106
+
107
+ def logits(self, tokens, **patch):
108
+ return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight)
109
+
110
+
111
+ def average_prefix_jacobian(view, prefixes, sender, *, chunk=32):
112
+ """E[d h_final,sender / d h_layer,sender], with labels absent from the graph.
113
+
114
+ A shared shift applied to all independent calibration prompts differentiates
115
+ their mean output, exactly averaging their Jacobians. Parameters need no
116
+ gradients. The endpoint is the residual before the final LayerNorm.
117
+ """
118
+ if any(p.requires_grad for p in view.model.parameters()):
119
+ raise ValueError("Freeze model parameters before constructing the lens")
120
+ with torch.no_grad():
121
+ x, boundaries = view.embed(prefixes), []
122
+ for block in view.blocks:
123
+ x, _, _ = view.parts(x, block, math_attention=True)
124
+ boundaries.append(x.detach())
125
+ jacobians = []
126
+ identity = torch.eye(view.width, device=view.device)
127
+ for layer, boundary in enumerate(boundaries):
128
+ shift = torch.zeros(view.width, device=view.device, requires_grad=True)
129
+ mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float()
130
+ x = boundary + mask[None, :, None] * shift[None, None, :]
131
+ for block in view.blocks[layer + 1 :]:
132
+ x, _, _ = view.parts(x, block, math_attention=True)
133
+ endpoint = x[:, sender].mean(0)
134
+ rows = []
135
+ for start in range(0, view.width, chunk):
136
+ rows.append(
137
+ torch.autograd.grad(
138
+ endpoint,
139
+ shift,
140
+ grad_outputs=identity[start : start + chunk],
141
+ is_grads_batched=True,
142
+ retain_graph=start + chunk < view.width,
143
+ )[0].detach()
144
+ )
145
+ jacobians.append(torch.cat(rows))
146
+ return torch.stack(jacobians)
147
+
148
+
149
+ def swap_coordinates(state, basis):
150
+ """Swap two coefficients in a nonorthogonal frame, preserving its complement."""
151
+ if basis.shape != (*state.shape, 2):
152
+ raise ValueError("Expected [example, width, two semantic axes]")
153
+ coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1)
154
+ difference = coefficients.flip(-1) - coefficients
155
+ return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype)
156
+
157
+
158
+ def projection(state, direction):
159
+ direction = F.normalize(direction, dim=-1)
160
+ return (state * direction).sum(-1, keepdim=True) * direction
161
+
162
+
163
+ def match_norm(delta, reference):
164
+ norm = delta.norm(dim=-1, keepdim=True)
165
+ if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()):
166
+ raise ValueError("Degenerate random control")
167
+ return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12)
168
+
169
+
170
+ def control_observation(changed, baseline):
171
+ """Record numerical control outcomes without silently dropping sensitive cases."""
172
+ mask = np.any(changed != baseline, axis=1)
173
+ return {
174
+ "n_queries": len(baseline),
175
+ "generated_rows_changed": int(mask.sum()),
176
+ "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()),
177
+ "changed_query_indices": np.flatnonzero(mask).tolist(),
178
+ "changed_fraction": float(mask.mean()),
179
+ "exact": bool(not mask.any()),
180
+ }
181
+
182
+
183
+ def _rank(seed, *values):
184
+ return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest()
185
+
186
+
187
+ def select_pairs(atoms, first_families, seed, per_family, *, ood=None):
188
+ """Choose prefixes/donors and all shared continuations using graph truth only.
189
+
190
+ Donors use the same r1 and first-fact family. Every pair has at least two
191
+ distinct shared r2 with different original/counterfactual tails. A pair is
192
+ selected before scoring; its exact same prefix intervention serves every r2.
193
+ """
194
+ atoms = np.asarray(atoms, dtype=np.int64)
195
+ outgoing, relation = defaultdict(dict), defaultdict(list)
196
+ for index, (head, r, tail) in enumerate(atoms):
197
+ if int(r) in outgoing[int(head)]:
198
+ raise ValueError("Ambiguous atomic truth")
199
+ outgoing[int(head)][int(r)] = (int(tail), index)
200
+ relation[int(r)].append(index)
201
+ groups, queries, coverage = [], [], {}
202
+ for name, indices in first_families.items():
203
+ allowed = set(map(int, indices))
204
+ eligible = []
205
+ for first in sorted(allowed):
206
+ head, r1, bridge = map(int, atoms[first])
207
+ candidates = []
208
+ for donor in relation[r1]:
209
+ dh, _, db = map(int, atoms[donor])
210
+ if donor not in allowed or dh == head or db == bridge:
211
+ continue
212
+ common = sorted(set(outgoing[bridge]) & set(outgoing[db]))
213
+ common = [
214
+ r
215
+ for r in common
216
+ if outgoing[bridge][r][0] != outgoing[db][r][0]
217
+ and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db}
218
+ ]
219
+ if len(common) >= 2:
220
+ candidates.append((donor, common))
221
+ if candidates:
222
+ donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0]))
223
+ eligible.append((first, donor, common))
224
+ eligible.sort(key=lambda v: _rank(seed, v[0]))
225
+ coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)}
226
+ for first, donor, common in eligible[:per_family]:
227
+ head, r1, bridge = map(int, atoms[first])
228
+ dh, _, db = map(int, atoms[donor])
229
+ group = len(groups)
230
+ groups.append([head, r1, bridge, dh, db, first, donor])
231
+ for r2 in common:
232
+ tail, second = outgoing[bridge][r2]
233
+ ct, cf_second = outgoing[db][r2]
234
+ kind = (
235
+ name
236
+ if ood is None
237
+ else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id")
238
+ )
239
+ queries.append((group, r2, tail, ct, second, cf_second, kind))
240
+ coverage[name]["selected"] = min(len(eligible), per_family)
241
+ if not groups:
242
+ raise ValueError("No graph-eligible cross-relation pairs; do not reroll")
243
+ return {
244
+ "groups": np.asarray(groups, dtype=np.int64),
245
+ "queries": np.asarray([r[:6] for r in queries], dtype=np.int64),
246
+ "strata": np.asarray([r[6] for r in queries]),
247
+ "counterfactual_strata": np.asarray(
248
+ [
249
+ r[6]
250
+ if ood is None
251
+ else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id")
252
+ for r in queries
253
+ ]
254
+ ),
255
+ "coverage": coverage,
256
+ }
257
+
258
+
259
+ def prefixes(facts, large, metadata):
260
+ facts = np.asarray(facts)
261
+ if large:
262
+ return np.column_stack(
263
+ (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"])
264
+ )
265
+ return np.column_stack(
266
+ (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1])
267
+ )
268
+
269
+
270
+ def prompts(rows, large, metadata):
271
+ if large:
272
+ from .grokking_reproduction import encode_rows
273
+
274
+ return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1]
275
+ from .text_pretrain import atomic_sentence, composite_sentence
276
+
277
+ render = atomic_sentence if rows.shape[1] == 3 else composite_sentence
278
+ length = 5 if rows.shape[1] == 3 else 7
279
+ return np.asarray([render(row)[:length] for row in rows])
280
+
281
+
282
+ def query_training_masks(world, payload, groups, queries, large):
283
+ """Count composition exposure without using scores or answer correctness."""
284
+ if large:
285
+ support = round(payload["spec"]["phi"] * (~world["ood"]).sum())
286
+ trained = world["chains"][world["train_order"][:support]][:, :3]
287
+ else:
288
+ trained = world["train_composite"][:, [0, 1, 3]]
289
+ trained = set(map(tuple, trained))
290
+ recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries])
291
+ donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries])
292
+ return {
293
+ "recipient_query_trained": recipient,
294
+ "counterfactual_query_trained": donor,
295
+ "both_queries_untrained": ~recipient & ~donor,
296
+ }
297
+
298
+
299
+ def load_task(spec, device):
300
+ payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False)
301
+ if "checkpoint_step" in spec:
302
+ saved_step = payload.get("step", payload["spec"].get("steps"))
303
+ assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step"
304
+ if spec["family"] == "reproduction":
305
+ from .grokking_reproduction import construct
306
+
307
+ data = Path(spec["data"])
308
+ metadata = json.loads((data / "complete.json").read_text())
309
+ model = construct(payload["spec"], metadata, device)
310
+ world = dict(np.load(data / "world.npz"))
311
+ panels = dict(np.load(data / "panels.npz"))
312
+ atoms = world["atoms"].astype(np.int64)
313
+ families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])}
314
+ ood = world["ood"]
315
+ entities = np.arange(
316
+ metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"]
317
+ )
318
+ else:
319
+ from .representation_alignment import new_model
320
+
321
+ model = new_model(payload["spec"], device)
322
+ world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz"))
323
+ metadata = {"entity_offset": 0}
324
+ atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"]))
325
+ families = {}
326
+ for name in ("familiar_test", "strict_test"):
327
+ firsts = set(map(tuple, world[name][:, :3]))
328
+ families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts])
329
+ ood = None
330
+ entities = np.arange(21, model.config.vocab_size)
331
+ panels = {k: world[k] for k in ("familiar_test", "strict_test")}
332
+ model.load_state_dict(payload["model"])
333
+ model.eval().requires_grad_(False)
334
+ return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels
335
+
336
+
337
+ @torch.no_grad()
338
+ def trace_in_batches(view, tokens, sender, batch_size, amp):
339
+ collected = []
340
+ for start in range(0, len(tokens), batch_size):
341
+ batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device)
342
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp):
343
+ _, trace = view.hidden(batch, sender=sender, capture=True)
344
+ collected.append(tuple(a.float() for a in trace))
345
+ return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3))
346
+
347
+
348
+ @torch.no_grad()
349
+ def generate(
350
+ view,
351
+ tokens,
352
+ targets,
353
+ counterfactual,
354
+ metadata,
355
+ batch_size,
356
+ *,
357
+ layer=None,
358
+ sender=None,
359
+ delta=None,
360
+ ):
361
+ """Greedy generation with feedback; scoring retains both target probabilities."""
362
+ offset = metadata["entity_offset"]
363
+ targets, counterfactual = targets + offset, counterfactual + offset
364
+ generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], []
365
+ for start in range(0, len(tokens), batch_size):
366
+ x = torch.as_tensor(tokens[start : start + batch_size], device=view.device)
367
+ patch = (
368
+ {}
369
+ if layer is None
370
+ else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]}
371
+ )
372
+ draws = []
373
+ for index in range(2 if view.large else 3):
374
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large):
375
+ logits = view.logits(x, **patch).float()
376
+ if index == 0:
377
+ logs = logits.log_softmax(-1)
378
+ arange = torch.arange(len(x), device=view.device)
379
+ original_logp.append(
380
+ logs[
381
+ arange,
382
+ torch.as_tensor(targets[start : start + batch_size], device=view.device),
383
+ ]
384
+ .cpu()
385
+ .numpy()
386
+ )
387
+ cf_logp.append(
388
+ logs[
389
+ arange,
390
+ torch.as_tensor(
391
+ counterfactual[start : start + batch_size], device=view.device
392
+ ),
393
+ ]
394
+ .cpu()
395
+ .numpy()
396
+ )
397
+ scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1)
398
+ top_ids.append(ids.cpu().numpy())
399
+ top_scores.append(scores.cpu().numpy())
400
+ answer = logits.argmax(-1)
401
+ draws.append(answer.cpu().numpy())
402
+ x = torch.cat((x, answer[:, None]), dim=1)
403
+ generated.append(np.stack(draws, axis=1))
404
+ return {
405
+ "generated": np.concatenate(generated),
406
+ "original_logp": np.concatenate(original_logp),
407
+ "cf_logp": np.concatenate(cf_logp),
408
+ "top_ids": np.concatenate(top_ids),
409
+ "top_logp": np.concatenate(top_scores),
410
+ }
411
+
412
+
413
+ def summarize(result, targets, counterfactual, metadata, strata, groups=None):
414
+ generated = result["generated"]
415
+ original = generated[:, 0] == targets + metadata["entity_offset"]
416
+ cf = generated[:, 0] == counterfactual + metadata["entity_offset"]
417
+ format_ok = (
418
+ generated[:, 1] == metadata["end_marker"]
419
+ if "end_marker" in metadata
420
+ else (generated[:, 1] == 5) & (generated[:, 2] == 1)
421
+ )
422
+ output = {}
423
+ for name in ("all", *sorted(set(strata))):
424
+ mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name
425
+ row = {
426
+ "n_queries": int(mask.sum()),
427
+ "answer_accuracy": float(original[mask].mean()),
428
+ "accuracy": float((original & format_ok)[mask].mean()),
429
+ "cf_answer_accuracy": float(cf[mask].mean()),
430
+ "cf_accuracy": float((cf & format_ok)[mask].mean()),
431
+ "format_accuracy": float(format_ok[mask].mean()),
432
+ "answer_nll": float(-result["original_logp"][mask].mean()),
433
+ "cf_nll": float(-result["cf_logp"][mask].mean()),
434
+ }
435
+ if groups is not None:
436
+ unique = np.unique(groups[mask])
437
+ row["n_first_facts"] = len(unique)
438
+ row["all_relations_cf_accuracy"] = float(
439
+ np.mean([cf[mask & (groups == g)].all() for g in unique])
440
+ )
441
+ row["mean_first_fact_cf_accuracy"] = float(
442
+ np.mean([cf[mask & (groups == g)].mean() for g in unique])
443
+ )
444
+ output[name] = row
445
+ return output
446
+
447
+
448
+ def run(spec, settings, out, gpu):
449
+ """Run one checkpoint with all execution layers, including failed interventions."""
450
+ out = Path(out)
451
+ out.mkdir(parents=True, exist_ok=True)
452
+ if (out / "run.json").exists():
453
+ raise FileExistsError(f"Do not overwrite an attempt: {out}")
454
+ torch.set_num_threads(1)
455
+ torch.set_num_interop_threads(1)
456
+ torch.cuda.set_device(gpu)
457
+ torch.backends.cuda.matmul.allow_tf32 = True
458
+ torch.backends.cudnn.allow_tf32 = True
459
+ device = torch.device(f"cuda:{gpu}")
460
+ began = time.perf_counter()
461
+ view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device)
462
+ digest_before = model_digest(view.model)
463
+ write_json(
464
+ out / "run.json",
465
+ {
466
+ "spec": {
467
+ **spec,
468
+ "settings": settings,
469
+ "checkpoint_step": payload.get("step", payload["spec"].get("steps")),
470
+ },
471
+ "checkpoint_sha256": file_hash(spec["checkpoint"]),
472
+ "initial_model_sha256": digest_before,
473
+ "world_sha256": file_hash(Path(spec["data"]) / "world.npz")
474
+ if view.large
475
+ else file_hash(Path(spec["checkpoint"]).parent / "world.npz"),
476
+ "job_type": "causal-intervention",
477
+ "pid": os.getpid(),
478
+ "gpu": gpu,
479
+ "gpu_name": torch.cuda.get_device_name(gpu),
480
+ "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32",
481
+ "parameters": sum(p.numel() for p in view.model.parameters()),
482
+ "vocab_size": len(view.embedding.weight),
483
+ "tags": ["bridge-workspace", spec["phase"], "no-training"],
484
+ "created_utc": utc(),
485
+ },
486
+ )
487
+ history, cursor = [], 0
488
+
489
+ def log(stage, metrics):
490
+ nonlocal cursor
491
+ history.append(
492
+ {
493
+ "step": cursor,
494
+ "metrics": metrics,
495
+ "wall_seconds": time.perf_counter() - began,
496
+ "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)),
497
+ }
498
+ )
499
+ write_json(out / "learning.json", history)
500
+ write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor})
501
+ print(
502
+ json.dumps(
503
+ {
504
+ "run": spec["name"],
505
+ "stage": stage,
506
+ "index": cursor,
507
+ "wall_seconds": history[-1]["wall_seconds"],
508
+ }
509
+ ),
510
+ flush=True,
511
+ )
512
+ cursor += 1
513
+
514
+ log("loaded", {})
515
+ pairs = select_pairs(
516
+ atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood
517
+ )
518
+ groups, q = pairs["groups"], pairs["queries"]
519
+ used_first = set(groups[:, 5]) | set(groups[:, 6])
520
+ calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first])
521
+ calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[
522
+ : settings["calibration_prompts"]
523
+ ]
524
+ sender = 1 if view.large else 3
525
+ cp = prefixes(atoms[calibration], view.large, metadata)
526
+ tensors = torch.as_tensor(cp, device=device)
527
+ jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"])
528
+ torch.save(
529
+ {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp},
530
+ out / "lens.pt",
531
+ )
532
+ log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)})
533
+ trace = trace_in_batches(
534
+ view,
535
+ prefixes(groups[:, :3], view.large, metadata),
536
+ sender,
537
+ settings["batch_size"],
538
+ view.large,
539
+ )
540
+ donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4]))
541
+ donor_states = trace_in_batches(
542
+ view,
543
+ prefixes(donor_facts, view.large, metadata),
544
+ sender,
545
+ settings["batch_size"],
546
+ view.large,
547
+ )[0]
548
+ rows = (
549
+ np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2]))
550
+ if view.large
551
+ else np.column_stack(
552
+ (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2])
553
+ )
554
+ )
555
+ tokens = prompts(rows, view.large, metadata)
556
+ training_masks = query_training_masks(world, payload, groups, q, view.large)
557
+ # Fix a native panel per stratum without consulting any predictions.
558
+ native_rows, native_strata = [], []
559
+ for name in (
560
+ ("test_ii", "test_io", "test_oi", "test_oo")
561
+ if view.large
562
+ else ("familiar_test", "strict_test")
563
+ ):
564
+ selected = panels[name][: settings["native_per_stratum"]]
565
+ native_rows.append(selected)
566
+ native_strata.extend([name] * len(selected))
567
+ native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata)
568
+ lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)}
569
+ native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]])
570
+ unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True)
571
+ fixed_entity = int(unique_bridges[bridge_counts.argmax()])
572
+ fixed_target = native_facts[:, 2] == fixed_entity
573
+ ntokens = prompts(native_rows, view.large, metadata)
574
+ ntrace = trace_in_batches(
575
+ view,
576
+ prefixes(native_facts, view.large, metadata),
577
+ sender,
578
+ settings["batch_size"],
579
+ view.large,
580
+ )
581
+ all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5])
582
+ for row, fact in zip(native_rows, native_facts, strict=True):
583
+ r2 = row[2] if view.large else row[3]
584
+ all_needed.add(lookup[int(fact[0]), int(fact[1])][1])
585
+ all_needed.add(lookup[int(fact[2]), int(r2)][1])
586
+ needed_ids = np.asarray(sorted(all_needed))
587
+ needed = atoms[needed_ids]
588
+ atrace = trace_in_batches(
589
+ view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large
590
+ )
591
+ torch.save(
592
+ {
593
+ "recipient": tuple(a.cpu() for a in trace),
594
+ "donor_states": donor_states.cpu(),
595
+ "native": tuple(a.cpu() for a in ntrace),
596
+ "atomic": tuple(a.cpu() for a in atrace),
597
+ },
598
+ out / "prefix-traces.pt",
599
+ )
600
+ atomic = generate(
601
+ view,
602
+ prompts(needed, view.large, metadata),
603
+ needed[:, -1],
604
+ needed[:, -1],
605
+ metadata,
606
+ settings["batch_size"],
607
+ )
608
+ atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"]
609
+ atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True))
610
+ prereq = np.asarray(
611
+ [
612
+ all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second))
613
+ for g, _, _, _, second, cf_second in q
614
+ ]
615
+ )
616
+ np.savez_compressed(
617
+ out / "selection.npz",
618
+ **{k: v for k, v in pairs.items() if k != "coverage"},
619
+ rows=rows,
620
+ native_rows=native_rows,
621
+ native_strata=native_strata,
622
+ fixed_entity=np.asarray(fixed_entity),
623
+ fixed_entity_target=fixed_target,
624
+ **training_masks,
625
+ prerequisite_correct=prereq,
626
+ needed_atomic_indices=needed_ids,
627
+ **{"atomic_" + k: v for k, v in atomic.items()},
628
+ )
629
+ write_json(out / "coverage.json", pairs["coverage"])
630
+ # Independent native implementation equivalence and prefix-causality audit.
631
+ audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device)
632
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large):
633
+ native = view.model(
634
+ audit_tokens,
635
+ positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device),
636
+ )[:, 0].float()
637
+ traced = view.logits(audit_tokens).float()
638
+ _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True)
639
+ causal_error = float(
640
+ (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max()
641
+ )
642
+ torch.testing.assert_close(
643
+ full_trace[0].float(),
644
+ trace[0][:, q[: len(audit_tokens), 0]],
645
+ atol=0.05 if view.large else 2e-5,
646
+ rtol=0.005 if view.large else 2e-5,
647
+ )
648
+ torch.testing.assert_close(
649
+ native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5
650
+ )
651
+ if not torch.equal(native.argmax(-1), traced.argmax(-1)):
652
+ raise AssertionError("Native/traced greedy answers differ")
653
+ summary = {}
654
+
655
+ def measure(
656
+ family,
657
+ condition,
658
+ layer,
659
+ input_tokens,
660
+ target,
661
+ cf_target,
662
+ strata,
663
+ delta=None,
664
+ query_groups=None,
665
+ ):
666
+ result = generate(
667
+ view,
668
+ input_tokens,
669
+ target,
670
+ cf_target,
671
+ metadata,
672
+ settings["batch_size"],
673
+ layer=layer if delta is not None else None,
674
+ sender=sender,
675
+ delta=delta,
676
+ )
677
+ np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result)
678
+ metrics = summarize(result, target, cf_target, metadata, strata, query_groups)
679
+ if family == "swap" and prereq.any():
680
+ metrics["prerequisites_correct"] = summarize(
681
+ {k: a[prereq] for k, a in result.items()},
682
+ target[prereq],
683
+ cf_target[prereq],
684
+ metadata,
685
+ strata[prereq],
686
+ query_groups[prereq],
687
+ )["all"]
688
+ if family == "swap" and training_masks["both_queries_untrained"].any():
689
+ mask = training_masks["both_queries_untrained"]
690
+ metrics["both_queries_untrained"] = summarize(
691
+ {k: a[mask] for k, a in result.items()},
692
+ target[mask],
693
+ cf_target[mask],
694
+ metadata,
695
+ strata[mask],
696
+ query_groups[mask],
697
+ )["all"]
698
+ if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"):
699
+ for label, mask in (
700
+ ("fixed_entity_target", fixed_target),
701
+ ("fixed_entity_unrelated", ~fixed_target),
702
+ ):
703
+ if mask.any():
704
+ metrics[label] = summarize(
705
+ {k: a[mask] for k, a in result.items()},
706
+ target[mask],
707
+ cf_target[mask],
708
+ metadata,
709
+ strata[mask],
710
+ )["all"]
711
+ summary[f"{family}/{condition}/{layer}"] = metrics
712
+ write_json(out / "summary.json", summary)
713
+ log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}})
714
+
715
+ measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0])
716
+ measure(
717
+ "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata
718
+ )
719
+ measure(
720
+ "atomic",
721
+ "baseline",
722
+ -1,
723
+ prompts(needed, view.large, metadata),
724
+ needed[:, -1],
725
+ needed[:, -1],
726
+ np.full(len(needed), "needed_atoms"),
727
+ )
728
+ states, attentions, mlps = trace
729
+ rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"])
730
+ rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng))
731
+ swap_errors, restore_errors = [], []
732
+ diagnostics = []
733
+ axis_families = settings.get("axis_families", ["prefix_jacobian"])
734
+ if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}:
735
+ raise ValueError("Unknown direction family")
736
+ for layer, jacobian, axis_family in (
737
+ (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families
738
+ ):
739
+ suffix = "_embedding" if axis_family == "input_embedding" else ""
740
+ directions = F.normalize(
741
+ view.embedding.weight[torch.as_tensor(entities, device=device)].float()
742
+ @ (torch.eye(view.width, device=device) if suffix else jacobian),
743
+ dim=-1,
744
+ )
745
+ index = {int(e): i for i, e in enumerate(entities)}
746
+ source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]]
747
+ dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]]
748
+ basis = torch.stack((source, dest), dim=-1)
749
+ swapped = swap_coordinates(states[layer], basis)
750
+ restored = swap_coordinates(swapped, basis)
751
+ swap_errors.append(float((restored - states[layer]).abs().max()))
752
+ random_basis = rotation[None] @ basis
753
+ swap_delta = swapped - states[layer]
754
+ torch.save(
755
+ {
756
+ "basis": basis.cpu(),
757
+ "rotation": rotation.cpu(),
758
+ "swap_delta": swap_delta.cpu(),
759
+ "axis_family": axis_family,
760
+ },
761
+ out / f"patch-{axis_family}-l{layer:02d}.pt",
762
+ )
763
+ deltas = {
764
+ "swap": swap_delta,
765
+ "swap_x2": 2 * swap_delta,
766
+ "random_swap": match_norm(
767
+ swap_coordinates(states[layer], random_basis) - states[layer], swap_delta
768
+ ),
769
+ "full_prefix": donor_states[layer] - states[layer],
770
+ "swap_back": restored - states[layer],
771
+ }
772
+ for condition in SWAPS:
773
+ measure(
774
+ "swap",
775
+ condition + suffix,
776
+ layer,
777
+ tokens,
778
+ q[:, 2],
779
+ q[:, 3],
780
+ pairs["strata"],
781
+ deltas[condition][q[:, 0]],
782
+ q[:, 0],
783
+ )
784
+ native_direction = directions[
785
+ [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]]
786
+ ]
787
+ native_state, native_attention, native_mlp = (a[layer] for a in ntrace)
788
+ fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][
789
+ None
790
+ ].expand_as(native_direction)
791
+ fixed_mlp = projection(native_mlp, fixed_direction)
792
+ removed_mlp = projection(native_mlp, native_direction)
793
+ # All sublayers still execute. Only the selected sender's semantic component
794
+ # is subtracted from the actual local update at the boundary.
795
+ local_restore = native_state - removed_mlp + removed_mlp
796
+ restore_errors.append(float((local_restore - native_state).abs().max()))
797
+ erasures = {
798
+ "erase_state": -projection(native_state, native_direction),
799
+ "erase_mlp": -removed_mlp,
800
+ "erase_attention": -projection(native_attention, native_direction),
801
+ "random_state": match_norm(
802
+ -projection(native_state, native_direction @ rotation.T),
803
+ -projection(native_state, native_direction),
804
+ ),
805
+ "random_mlp": match_norm(
806
+ -projection(native_mlp, native_direction @ rotation.T), -removed_mlp
807
+ ),
808
+ "random_attention": match_norm(
809
+ -projection(native_attention, native_direction @ rotation.T),
810
+ -projection(native_attention, native_direction),
811
+ ),
812
+ "restore_mlp": local_restore - native_state,
813
+ "fixed_entity_mlp": -fixed_mlp,
814
+ "fixed_entity_random_mlp": match_norm(
815
+ -projection(native_mlp, fixed_direction @ rotation.T),
816
+ -fixed_mlp,
817
+ ),
818
+ }
819
+ for condition in ERASURES:
820
+ measure(
821
+ "native",
822
+ condition + suffix,
823
+ layer,
824
+ ntokens,
825
+ native_rows[:, -1],
826
+ native_rows[:, -1],
827
+ native_strata,
828
+ erasures[condition],
829
+ )
830
+ # Relevant single-hop facts are scored under exactly the same local deletion.
831
+ adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]]
832
+ atomic_delta = -projection(atrace[2][layer], adirection)
833
+ measure(
834
+ "atomic",
835
+ "erase_mlp" + suffix,
836
+ layer,
837
+ prompts(needed, view.large, metadata),
838
+ needed[:, -1],
839
+ needed[:, -1],
840
+ np.full(len(needed), "needed_atoms"),
841
+ atomic_delta,
842
+ )
843
+ with torch.no_grad():
844
+ raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1)
845
+ lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1)
846
+ diagnostics.append(
847
+ {
848
+ "layer": layer,
849
+ "axis_family": axis_family,
850
+ "native_bridge_readout_accuracy": float(
851
+ (
852
+ raw
853
+ == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device)
854
+ )
855
+ .float()
856
+ .mean()
857
+ ),
858
+ "prefix_jacobian_bridge_readout_accuracy": float(
859
+ (
860
+ lens
861
+ == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device)
862
+ )
863
+ .float()
864
+ .mean()
865
+ ),
866
+ "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()),
867
+ "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()),
868
+ }
869
+ )
870
+ digest_after = model_digest(view.model)
871
+ if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()):
872
+ raise AssertionError("Intervention changed model parameters or accumulated gradients")
873
+ write_json(
874
+ out / "implementation-audit.json",
875
+ {
876
+ "parameters_unchanged": True,
877
+ "native_tracer_max_logit_error": float((native - traced).abs().max()),
878
+ "prefix_causal_state_max_error": causal_error,
879
+ "swap_inverse_max_errors": swap_errors,
880
+ "mlp_restore_max_errors": restore_errors,
881
+ "n_needed_atomic_facts": len(needed),
882
+ "needed_atomic_answer_accuracy": float(atomic_ok.mean()),
883
+ "swap_prerequisite_query_coverage": float(prereq.mean()),
884
+ "scoring": (
885
+ "greedy feedback, original/counterfactual answer plus termination; "
886
+ "query and first-fact denominators separate"
887
+ ),
888
+ },
889
+ )
890
+ write_json(out / "diagnostics.json", diagnostics)
891
+ log("complete", {"complete": {"evaluations": len(summary)}})
892
+ write_json(
893
+ out / "interventions-complete.json",
894
+ {
895
+ "finished_utc": utc(),
896
+ "evaluations": len(summary),
897
+ "model_sha256": digest_after,
898
+ "wall_seconds": time.perf_counter() - began,
899
+ "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device),
900
+ "new_training_updates": 0,
901
+ },
902
+ )
903
+ write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1})
904
+
905
+
906
+ def audit_run(out, gpu):
907
+ """Reload in an independent process and reproduce fixed raw prediction subsets."""
908
+ out = Path(out)
909
+ torch.set_num_threads(1)
910
+ torch.set_num_interop_threads(1)
911
+ torch.cuda.set_device(gpu)
912
+ torch.backends.cuda.matmul.allow_tf32 = True
913
+ torch.backends.cudnn.allow_tf32 = True
914
+ metadata_run = json.loads((out / "run.json").read_text())
915
+ spec = metadata_run["spec"]
916
+ settings = spec["settings"]
917
+ view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}")
918
+ assert model_digest(view.model) == metadata_run["initial_model_sha256"]
919
+ assert os.getpid() != metadata_run["pid"], "Reload must use a separate process"
920
+ selection = dict(np.load(out / "selection.npz"))
921
+ groups, queries = selection["groups"], selection["queries"]
922
+ jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[
923
+ "jacobians"
924
+ ]
925
+ sender = 1 if view.large else 3
926
+ trace = trace_in_batches(
927
+ view,
928
+ prefixes(groups[:, :3], view.large, metadata),
929
+ sender,
930
+ settings["batch_size"],
931
+ view.large,
932
+ )
933
+ states = trace[0]
934
+ native_rows = selection["native_rows"]
935
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
936
+ facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]])
937
+ ntrace = trace_in_batches(
938
+ view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large
939
+ )
940
+ swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int))
941
+ native_indices = np.unique(
942
+ np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int)
943
+ )
944
+ summary = json.loads((out / "summary.json").read_text())
945
+ comparisons, max_logp_error, identity_controls = [], 0.0, []
946
+
947
+ def check(family, condition, layer, indices, rows, target, cf, delta=None):
948
+ nonlocal max_logp_error
949
+
950
+ # Baseline is independently executed through the model's own forward.
951
+ class NativeView(ModelView):
952
+ def logits(self, tokens, **_):
953
+ positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device)
954
+ return self.model(tokens, positions=positions)[:, 0]
955
+
956
+ actual = generate(
957
+ NativeView(view.model) if condition == "baseline" else view,
958
+ prompts(rows, view.large, metadata),
959
+ target,
960
+ cf,
961
+ metadata,
962
+ settings["batch_size"],
963
+ layer=layer if delta is not None else None,
964
+ sender=sender,
965
+ delta=delta,
966
+ )
967
+ # Preserve original batch shapes: compacting selected rows changes BF16
968
+ # GEMM rounding. Select the audit subset only after the full generation.
969
+ actual = {key: value[indices] for key, value in actual.items()}
970
+ expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz"))
971
+ if not np.array_equal(actual["generated"], expected["generated"][indices]):
972
+ raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}")
973
+ for key in ("original_logp", "cf_logp"):
974
+ error = float(np.max(np.abs(actual[key] - expected[key][indices])))
975
+ max_logp_error = max(max_logp_error, error)
976
+ np.testing.assert_allclose(
977
+ actual[key],
978
+ expected[key][indices],
979
+ atol=0.04 if view.large else 3e-5,
980
+ rtol=0.002 if view.large else 2e-5,
981
+ )
982
+ comparisons.append(
983
+ {"family": family, "condition": condition, "layer": layer, "queries": len(indices)}
984
+ )
985
+
986
+ check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3])
987
+ check(
988
+ "native",
989
+ "baseline",
990
+ -1,
991
+ native_indices,
992
+ native_rows,
993
+ native_rows[:, -1],
994
+ native_rows[:, -1],
995
+ )
996
+ entity_index = {int(e): i for i, e in enumerate(entities)}
997
+ for layer, jacobian in enumerate(jacobians):
998
+ for axis_family in settings.get("axis_families", ["prefix_jacobian"]):
999
+ suffix = "_embedding" if axis_family == "input_embedding" else ""
1000
+ directions = F.normalize(
1001
+ view.embedding.weight[torch.as_tensor(entities, device=view.device)].float()
1002
+ @ (torch.eye(view.width, device=view.device) if suffix else jacobian),
1003
+ dim=-1,
1004
+ )
1005
+ source = directions[
1006
+ [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]
1007
+ ]
1008
+ dest = directions[
1009
+ [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]
1010
+ ]
1011
+ delta = (
1012
+ swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer]
1013
+ )
1014
+ check(
1015
+ "swap",
1016
+ "swap" + suffix,
1017
+ layer,
1018
+ swap_indices,
1019
+ selection["rows"],
1020
+ queries[:, 2],
1021
+ queries[:, 3],
1022
+ delta[queries[:, 0]],
1023
+ )
1024
+ native_direction = directions[
1025
+ [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]]
1026
+ ]
1027
+ native_delta = -projection(ntrace[2][layer], native_direction)
1028
+ check(
1029
+ "native",
1030
+ "erase_mlp" + suffix,
1031
+ layer,
1032
+ native_indices,
1033
+ native_rows,
1034
+ native_rows[:, -1],
1035
+ native_rows[:, -1],
1036
+ native_delta,
1037
+ )
1038
+ # Structural and numerical controls must retain native generation.
1039
+ for family, condition in (
1040
+ ("swap", "swap_back" + suffix),
1041
+ ("native", "restore_mlp" + suffix),
1042
+ ):
1043
+ raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"]
1044
+ baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"]
1045
+ identity_controls.append(
1046
+ {
1047
+ "family": family,
1048
+ "condition": condition,
1049
+ "layer": layer,
1050
+ **control_observation(raw, baseline),
1051
+ }
1052
+ )
1053
+ if layer == len(view.blocks) - 1:
1054
+ for key in summary:
1055
+ family, condition, occurrence = key.split("/")
1056
+ if int(occurrence) != layer or family == "atomic":
1057
+ continue
1058
+ raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"]
1059
+ baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"]
1060
+ assert np.array_equal(raw, baseline), (
1061
+ key,
1062
+ "final sender must not affect later positions",
1063
+ )
1064
+ assert model_digest(view.model) == metadata_run["initial_model_sha256"]
1065
+ previous = out / "implementation-audit.json"
1066
+ if not previous.exists() and (out / "audit.json").exists():
1067
+ previous.write_bytes((out / "audit.json").read_bytes())
1068
+ write_json(
1069
+ out / "audit.json",
1070
+ {
1071
+ "independent_process": True,
1072
+ "pid": os.getpid(),
1073
+ "gpu": gpu,
1074
+ "finished_utc": utc(),
1075
+ "parameters_unchanged": True,
1076
+ "generations_exact": True,
1077
+ "identity_controls_exact": all(c["exact"] for c in identity_controls),
1078
+ "identity_control_observations": identity_controls,
1079
+ "scope": (
1080
+ "Fixed subset reload predictions exact; numerical inverse/restore "
1081
+ "outcomes recorded separately"
1082
+ ),
1083
+ "max_log_probability_error": max_logp_error,
1084
+ "evaluations": comparisons,
1085
+ "implementation_audit_sha256": file_hash(previous),
1086
+ "audit_source_sha256": file_hash(__file__),
1087
+ },
1088
+ )
1089
+ if (out / "interventions-complete.json").exists():
1090
+ complete = json.loads((out / "interventions-complete.json").read_text())
1091
+ complete["independently_reloaded"] = True
1092
+ complete["audit_finished_utc"] = utc()
1093
+ write_json(out / "complete.json", complete)
1094
+ write_json(
1095
+ out / "status.json",
1096
+ {
1097
+ "state": "complete",
1098
+ "independently_reloaded": True,
1099
+ "step": json.loads((out / "learning.json").read_text())[-1]["step"],
1100
+ },
1101
+ )
1102
+ print(
1103
+ json.dumps(
1104
+ {
1105
+ "run": out.name,
1106
+ "independent_reload": "passed",
1107
+ "evaluations": len(comparisons),
1108
+ "max_log_probability_error": max_logp_error,
1109
+ }
1110
+ ),
1111
+ flush=True,
1112
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_controls.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controls separating knowledge load, derived supervision, and serial recall."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from .capacity_scaling import DIGIT, EOS, TYPE_B
8
+
9
+
10
+ def training_indices(world, spec, epoch):
11
+ """Keep the historical mixed stream exactly, or replace derived examples.
12
+
13
+ Replay preserves the mixed stream's batch sizes/updates and each original
14
+ atomic slot. Extra slots carry balanced atomic replay, never held-out labels.
15
+ """
16
+ atoms = len(world["atomic"])
17
+ mixed = atoms + len(world["train_composition"])
18
+ mode = spec.get("training_mode", "mixed")
19
+ if mode not in {"mixed", "atomic", "atomic_replay"}:
20
+ raise ValueError(mode)
21
+ n = atoms if mode == "atomic" else mixed
22
+ rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch]))
23
+ order = rng.permutation(n)
24
+ if mode == "atomic_replay":
25
+ replay_rng = np.random.default_rng(
26
+ np.random.SeedSequence([spec["stream_seed"], epoch, 771])
27
+ )
28
+ replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms)
29
+ source = np.concatenate((np.arange(atoms), replacements))
30
+ return source[order]
31
+ return order
32
+
33
+
34
+ def decode_bridge(predictions):
35
+ """Reject malformed/out-of-domain predictions instead of oracle repairing."""
36
+ p = np.asarray(predictions)
37
+ d = p[:, 1:5] - DIGIT
38
+ valid = (
39
+ (p[:, 0] == TYPE_B)
40
+ & (p[:, 5] == EOS)
41
+ & ((d >= 0) & (d < 16)).all(1)
42
+ & (d[:, :2] == 0).all(1)
43
+ )
44
+ values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1)
45
+ return np.where(valid, values, 0), valid
46
+
47
+
48
+ def first_queries(compositions):
49
+ rows = np.zeros_like(compositions)
50
+ rows[:, 0] = 0
51
+ rows[:, 1:3] = compositions[:, 1:3]
52
+ rows[:, 3] = -1
53
+ rows[:, 5:] = -1
54
+ return rows
55
+
56
+
57
+ def second_queries(compositions, bridges):
58
+ rows = np.zeros_like(compositions)
59
+ rows[:, 0] = 1
60
+ rows[:, 1] = bridges
61
+ rows[:, 2] = compositions[:, 3]
62
+ rows[:, 3] = -1
63
+ rows[:, 5:] = -1
64
+ return rows
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_scaling.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-vocabulary random worlds for the capacity development experiment.
2
+
3
+ Knowledge is in independent A->B and B->C maps. Composition labels are derived,
4
+ never counted as independent information. This is a QA adaptation, not bioS.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import math
11
+
12
+ import numpy as np
13
+
14
+ PAD, BOS, EOS, ANSWER = 0, 1, 2, 3
15
+ TYPE_A, TYPE_B, TYPE_C = 4, 5, 6
16
+ DIGIT, REL_A, REL_B = 7, 23, 27
17
+ VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6
18
+
19
+
20
+ def digest_arrays(arrays):
21
+ h = hashlib.sha256()
22
+ for key, value in sorted(arrays.items()):
23
+ value = np.ascontiguousarray(value)
24
+ h.update(key.encode())
25
+ h.update(str(value.shape).encode())
26
+ h.update(str(value.dtype).encode())
27
+ h.update(value.tobytes())
28
+ return h.hexdigest()
29
+
30
+
31
+ def generate_world(spec):
32
+ """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2.
33
+
34
+ The maximum address universe and all maps are generated before choosing a
35
+ load. Prefix worlds are nested. Background controls keep the entire low-load
36
+ composition training/evaluation sets, including necessary facts, unchanged.
37
+ """
38
+ seed, heads = spec["world_seed"], spec["heads_n"]
39
+ maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"]
40
+ if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4):
41
+ raise ValueError("This version requires 256 values, four relations, <=65536 heads")
42
+ support_heads = spec.get("support_heads_n", heads)
43
+ if not 1 <= support_heads <= heads:
44
+ raise ValueError("Invalid support prefix")
45
+
46
+ def rng(part):
47
+ return np.random.default_rng(np.random.SeedSequence([seed, part]))
48
+
49
+ first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads]
50
+ second = rng(1).integers(values, size=(values, relations), dtype=np.int64)
51
+ eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75
52
+ eligible_second = rng(3).random((values, relations)) < 0.75
53
+ first_n = heads * relations
54
+ h, r = np.indices(first.shape).reshape(2, -1)
55
+ atoms_a = np.column_stack(
56
+ (
57
+ np.zeros(first_n, dtype=int),
58
+ h,
59
+ r,
60
+ -np.ones(first_n, dtype=int),
61
+ first.ravel(),
62
+ np.arange(first_n),
63
+ -np.ones(first_n, dtype=int),
64
+ )
65
+ )
66
+ b, r2 = np.indices(second.shape).reshape(2, -1)
67
+ second_n = second.size
68
+ atoms_b = np.column_stack(
69
+ (
70
+ np.ones(second_n, dtype=int),
71
+ b,
72
+ r2,
73
+ -np.ones(second_n, dtype=int),
74
+ second.ravel(),
75
+ first_n + np.arange(second_n),
76
+ -np.ones(second_n, dtype=int),
77
+ )
78
+ )
79
+ atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64)
80
+ h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1)
81
+ bridge = first[h, r1]
82
+ a_id, b_id = h * relations + r1, first_n + bridge * relations + r2
83
+ comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype(
84
+ np.int64
85
+ )
86
+ train_mask = (
87
+ eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2)
88
+ )
89
+ trained = np.zeros(len(atoms), dtype=bool)
90
+ trained[comps[train_mask, 5:].ravel()] = True
91
+ seen1, seen2 = trained[a_id], trained[b_id]
92
+ world = {
93
+ "first": first,
94
+ "second": second,
95
+ "atomic": atoms,
96
+ "train_composition": comps[train_mask],
97
+ }
98
+ for name, mask in {
99
+ "II": seen1 & seen2,
100
+ "IO": seen1 & ~seen2,
101
+ "OI": ~seen1 & seen2,
102
+ "OO": ~seen1 & ~seen2,
103
+ }.items():
104
+ ids = np.flatnonzero(mask & ~train_mask)
105
+ # Selection stream does not depend on load in fixed-target controls.
106
+ take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids)
107
+ world[name] = comps[take[: spec["evaluation_per_pool"]]]
108
+ world[name + "_population"] = np.array([len(ids)], dtype=np.int64)
109
+ panel_rng = rng(30)
110
+ for name in ("atomic", "train_composition"):
111
+ ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]]
112
+ world[name + "_panel"] = world[name][ids]
113
+ world["role_counts"] = np.stack(
114
+ [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)]
115
+ )
116
+ return world
117
+
118
+
119
+ def digits(values):
120
+ values = np.asarray(values, dtype=np.int64)
121
+ return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15)
122
+
123
+
124
+ def pack(rows):
125
+ """Right padding is causally downstream; only answer+EOS is supervised."""
126
+ rows = np.asarray(rows, dtype=np.int64)
127
+ x = np.zeros((len(rows), CONTEXT), dtype=np.int64)
128
+ composition = rows[:, 0] == 2
129
+ prefix_length = np.where(composition, 9, 8)
130
+ x[:, 0] = BOS
131
+ x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A)
132
+ x[:, 2:6] = digits(rows[:, 1])
133
+ x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2]
134
+ x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER)
135
+ x[composition, 8] = ANSWER
136
+ labels = np.column_stack(
137
+ (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS))
138
+ )
139
+ positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH)
140
+ x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1]
141
+ return x, positions, labels
142
+
143
+
144
+ def information_ledger(world, parameters, knowledge_nll=None):
145
+ facts = len(world["atomic"])
146
+ bits = facts * math.log2(world["second"].shape[0])
147
+ result = {
148
+ "independent_facts": facts,
149
+ "world_bits": bits,
150
+ "parameters": parameters,
151
+ "adjusted_parameters": parameters,
152
+ "data_bits_per_parameter": bits / parameters,
153
+ "composition_independent_bits": 0,
154
+ }
155
+ if knowledge_nll is not None:
156
+ learned = bits - facts * knowledge_nll / math.log(2)
157
+ result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters)
158
+ return result
159
+
160
+
161
+ def model_parameter_count(width, layers=2):
162
+ # Tied token/output weights, learned positions, two biased projections each
163
+ # in attention/MLP, per-block and final LayerNorms.
164
+ return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width
165
+
166
+
167
+ def prerequisite_pass(metrics, thresholds):
168
+ return all(
169
+ metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II")
170
+ )
171
+
172
+
173
+ def grid_capacity(points, metric, threshold, atomic_threshold):
174
+ """Report sampled successes and censoring, never silently assume monotonicity."""
175
+ points = sorted(points, key=lambda p: p["bits"])
176
+ passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points]
177
+ reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed)))
178
+ successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok]
179
+ lower = max(successes) if successes else None
180
+ failures_above = [
181
+ p["bits"]
182
+ for p, ok in zip(points, passed, strict=True)
183
+ if not ok and (lower is None or p["bits"] > lower)
184
+ ]
185
+ return {
186
+ "largest_observed_passing_bits": lower,
187
+ "next_observed_failing_bits": min(failures_above) if failures_above else None,
188
+ "nonmonotonic_grid": reversals,
189
+ "interpretation": "sampled_grid_only; bracket requires monotone interpolation",
190
+ "censoring": "below_grid"
191
+ if lower is None
192
+ else ("above_grid" if not failures_above else "bracketed_on_grid"),
193
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/cli.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command-line interface for the deterministic matrix illustration."""
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from .experiments import run_minimal_example
8
+
9
+
10
+ def main(argv: list[str] | None = None) -> int:
11
+ """Print the analytical report as JSON and optionally save a copy."""
12
+ parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.")
13
+ parser.add_argument(
14
+ "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2"
15
+ )
16
+ parser.add_argument(
17
+ "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance"
18
+ )
19
+ parser.add_argument(
20
+ "--output", type=Path, help="also save JSON to this path (creates parent directories)"
21
+ )
22
+ args = parser.parse_args(argv)
23
+ try:
24
+ report = run_minimal_example(rank=args.rank, atol=args.atol)
25
+ serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False)
26
+ if args.output is not None:
27
+ args.output.parent.mkdir(parents=True, exist_ok=True)
28
+ args.output.write_text(serialized + "\n", encoding="utf-8")
29
+ except (ValueError, OSError) as exc:
30
+ parser.error(str(exc))
31
+ print(serialized)
32
+ return 0
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/composition_curves.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distinct composition support and knowledge-load curves on random relation graphs.
2
+
3
+ The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously
4
+ successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps
5
+ parameters identical across loads. Development and confirmation worlds differ.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import os
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import torch
19
+
20
+ from .bios_model import ModelConfig, matmul_flops
21
+ from .grok_depth import (
22
+ EpochStream,
23
+ GraphStep,
24
+ SmallGPT,
25
+ evaluate_rows,
26
+ make_optimizer,
27
+ pack_rows,
28
+ two_calls,
29
+ utc,
30
+ write_json,
31
+ )
32
+ from .grok_depth_data import audit_world, build_world
33
+
34
+
35
+ def sha256(path):
36
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
37
+
38
+
39
+ def array_hash(arrays):
40
+ digest = hashlib.sha256()
41
+ for name, value in sorted(arrays.items()):
42
+ digest.update(name.encode())
43
+ digest.update(np.asarray(value.shape, dtype="<i8").tobytes())
44
+ digest.update(value.astype("<i8", copy=False).tobytes())
45
+ return digest.hexdigest()
46
+
47
+
48
+ def prepare_world(spec):
49
+ """Reserve once, permute once, take nested prefixes; never repeat support rows."""
50
+ n = spec["entities"]
51
+ maximum = spec["max_entities"]
52
+ if not 1 <= n <= maximum:
53
+ raise ValueError("Entity count must fit the fixed vocabulary")
54
+ base = build_world(
55
+ spec["world_seed"],
56
+ entities=n,
57
+ relations=spec["relations"],
58
+ degree=spec["degree"],
59
+ phi=0,
60
+ id_fraction=spec["id_fraction"],
61
+ id_test_fraction=spec["test_fraction"],
62
+ )
63
+ audit_world(base)
64
+ rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960601]))
65
+ order = rng.permutation(len(base["unused_composite"]))
66
+ requested = round(spec["phi"] * len(base["id_atomic"]))
67
+ if requested > len(order):
68
+ raise ValueError("Distinct support request exceeds the reserved training pool")
69
+ arrays = {
70
+ key: base[key].copy()
71
+ for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite")
72
+ }
73
+ eligible = base["unused_composite"][order].copy()
74
+ for rows in [*arrays.values(), eligible]:
75
+ rows[:, 1:-1] += maximum - n
76
+ identity = array_hash({**arrays, "eligible": eligible})
77
+ arrays["train_composite"] = eligible[:requested].copy()
78
+ lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64)
79
+ atomic = arrays["atomic"]
80
+ lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic))
81
+ first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum)
82
+ first_counts = np.bincount(first, minlength=len(atomic))
83
+ second_counts = np.bincount(second, minlength=len(atomic))
84
+ role = {}
85
+ for name in ("test_composite", "ood_composite"):
86
+ one, two = constituent_indices(arrays[name], atomic, lookup, maximum)
87
+ role[name] = {
88
+ "n": len(one),
89
+ "both_facts_seen_in_required_roles": (
90
+ float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean())
91
+ if len(one)
92
+ else None
93
+ ),
94
+ }
95
+ panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602]))
96
+ panels = {}
97
+ for key, name in [
98
+ ("atomic", "atomic"),
99
+ ("id_atomic", "atomic_id"),
100
+ ("ood_atomic", "atomic_ood"),
101
+ ("test_composite", "II"),
102
+ ("ood_composite", "OO"),
103
+ ]:
104
+ rows = arrays[key]
105
+ ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False)
106
+ panels[name] = rows[ids].copy()
107
+ panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy()
108
+ metadata = {
109
+ "world_seed": spec["world_seed"],
110
+ "entities": n,
111
+ "max_entities": maximum,
112
+ "relations": spec["relations"],
113
+ "degree": spec["degree"],
114
+ "vocab_size": maximum + spec["relations"] + 2,
115
+ "atomic_examples": len(atomic),
116
+ "id_atomic_examples": len(arrays["id_atomic"]),
117
+ "composition_examples": requested,
118
+ "eligible_compositions": len(eligible),
119
+ "phi_actual": requested / len(arrays["id_atomic"]),
120
+ "world_sha256": identity,
121
+ "dataset_sha256": array_hash(arrays),
122
+ "knowledge_bits": len(atomic) * math.log2(n),
123
+ "entropy_condition": "independent uniform tails, conditional on head/relation keys",
124
+ "composition_additional_independent_bits": 0,
125
+ "role_coverage": role,
126
+ "panel_counts": {key: len(value) for key, value in panels.items()},
127
+ "full_counts": {key: len(value) for key, value in arrays.items()},
128
+ "graph_source": base["metadata"]["source_url"],
129
+ "graph_source_commit": base["metadata"]["source_commit"],
130
+ "graph_audit": base["metadata"]["dataset_sha256"],
131
+ }
132
+ return arrays, panels, metadata
133
+
134
+
135
+ def constituent_indices(rows, atomic, lookup, maximum):
136
+ first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2]
137
+ if np.any(first < 0):
138
+ raise ValueError("Unknown first-hop fact")
139
+ second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2]
140
+ if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]):
141
+ raise ValueError("Composition truth differs from graph traversal")
142
+ return first, second
143
+
144
+
145
+ def budget_nodes(spec, total):
146
+ matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"])
147
+ compute = spec["compute_steps"]
148
+ end = spec.get("fixed_steps", max(compute, matched))
149
+ nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)}
150
+ nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end)
151
+ nodes.update(range(192000, end, 64000))
152
+ return sorted(nodes), {"compute": compute, "exposure": matched, "end": end}
153
+
154
+
155
+ def construct(spec, device):
156
+ torch.manual_seed(spec["initialization"])
157
+ cfg = ModelConfig(
158
+ vocab_size=spec["max_entities"] + spec["relations"] + 2,
159
+ width=spec["width"],
160
+ layers=spec["layers"],
161
+ heads=spec["heads"],
162
+ context=8,
163
+ )
164
+ return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg
165
+
166
+
167
+ def model_hash(model):
168
+ digest = hashlib.sha256()
169
+ for name, tensor in model.state_dict().items():
170
+ digest.update(name.encode())
171
+ digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
172
+ return digest.hexdigest()
173
+
174
+
175
+ def measure(model, panels, device):
176
+ metrics, predictions = {}, {}
177
+ for name, rows in panels.items():
178
+ metrics[name], values = evaluate_rows(model, rows, device, batch_size=512)
179
+ if len(rows):
180
+ metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean())
181
+ predictions.update({name + "_" + key: value for key, value in values.items()})
182
+ return metrics, predictions
183
+
184
+
185
+ def train(spec, out, resume=False):
186
+ out = Path(out)
187
+ torch.set_num_threads(1)
188
+ torch.set_num_interop_threads(1)
189
+ torch.backends.cuda.matmul.allow_tf32 = True
190
+ torch.backends.cudnn.allow_tf32 = True
191
+ device = torch.device("cuda:0")
192
+ torch.cuda.set_device(device)
193
+ arrays, panels, data = prepare_world(spec)
194
+ model, cfg = construct(spec, device)
195
+ lr = torch.tensor(spec["lr"], device=device)
196
+ optimizer = make_optimizer(model, lr, spec["weight_decay"])
197
+ packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")]
198
+ table = tuple(
199
+ torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True)
200
+ )
201
+ atomic_n, composition_n = data["atomic_examples"], data["composition_examples"]
202
+ total = atomic_n + composition_n
203
+ stream = EpochStream(total, spec["stream_seed"])
204
+ nodes, budgets = budget_nodes(spec, total)
205
+ start, seconds = 0, 0.0
206
+ counts = {"atomic": 0, "composition": 0}
207
+ initial_hash = model_hash(model)
208
+ if resume:
209
+ saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
210
+ if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]:
211
+ raise ValueError("Resume identity mismatch")
212
+ model.load_state_dict(saved["model"])
213
+ optimizer.load_state_dict(saved["optimizer"])
214
+ lr = optimizer.param_groups[0]["lr"]
215
+ for group in optimizer.param_groups:
216
+ group["lr"] = lr
217
+ stream.load_state_dict(saved["stream"])
218
+ counts, seconds, start = saved["counts"], saved["seconds"], saved["step"]
219
+ torch.set_rng_state(saved["cpu_rng"].cpu())
220
+ torch.cuda.set_rng_state(saved["cuda_rng"].cpu())
221
+ initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"]
222
+ out.mkdir(parents=True, exist_ok=True)
223
+ metadata = {
224
+ "spec": spec,
225
+ "phase": spec["phase"],
226
+ "pid": os.getpid(),
227
+ "gpu": int(os.environ.get("PHYSICAL_GPU", 0)),
228
+ "gpu_name": torch.cuda.get_device_name(),
229
+ "parameters": sum(p.numel() for p in model.parameters()),
230
+ "initial_model_sha256": initial_hash,
231
+ "world_sha256": data["world_sha256"],
232
+ "dtype": "FP32 parameters/optimizer/forward; TF32 matmul",
233
+ "torch": torch.__version__,
234
+ "numpy": np.__version__,
235
+ "budgets": budgets,
236
+ "evaluation_nodes": nodes,
237
+ **data,
238
+ }
239
+ write_json(out / "run.json", metadata)
240
+ write_json(out / "data-audit.json", data)
241
+ np.savez_compressed(out / "world.npz", **arrays)
242
+ np.savez_compressed(out / "panels.npz", **panels)
243
+ t0 = time.perf_counter()
244
+ graph = GraphStep(model, optimizer, table, spec["batch_size"])
245
+ capture = time.perf_counter() - t0
246
+ per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True)
247
+ history = json.loads((out / "learning.json").read_text()) if resume else []
248
+ history = [record for record in history if record["step"] <= start]
249
+ begun = time.perf_counter()
250
+
251
+ def checkpoint(step, loss=None):
252
+ metrics, predictions = measure(model, panels, device)
253
+ record = {
254
+ "step": step,
255
+ "utc": utc(),
256
+ "metrics": metrics,
257
+ "training_seconds": seconds,
258
+ "wall_seconds": time.perf_counter() - begun,
259
+ "capture_seconds": capture,
260
+ "examples": step * spec["batch_size"],
261
+ "atomic_examples_seen": counts["atomic"],
262
+ "composition_examples_seen": counts["composition"],
263
+ "atomic_epochs": counts["atomic"] / atomic_n,
264
+ "composition_epochs": counts["composition"] / composition_n if composition_n else 0,
265
+ "minimum_record_exposures": (step * spec["batch_size"]) // total,
266
+ "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total),
267
+ "supervised_tokens": step * spec["batch_size"] * 2,
268
+ "executed_input_tokens": step * spec["batch_size"] * 4,
269
+ "estimated_matmul_training_flops": step * per_step,
270
+ "loss": loss,
271
+ "learning_rate": float(lr.detach()),
272
+ }
273
+ history.append(record)
274
+ write_json(out / "learning.json", history)
275
+ payload = {
276
+ "spec": spec,
277
+ "world_sha256": data["world_sha256"],
278
+ "step": step,
279
+ "model": model.state_dict(),
280
+ "optimizer": optimizer.state_dict(),
281
+ "stream": stream.state_dict(),
282
+ "counts": counts,
283
+ "seconds": seconds,
284
+ "cpu_rng": torch.get_rng_state(),
285
+ "cuda_rng": torch.cuda.get_rng_state(),
286
+ }
287
+ torch.save(payload, out / "latest.tmp.pt")
288
+ (out / "latest.tmp.pt").replace(out / "latest.pt")
289
+ if step in budgets.values():
290
+ torch.save(
291
+ {"spec": spec, "step": step, "model": model.state_dict()},
292
+ out / f"weights-{step}.pt",
293
+ )
294
+ np.savez_compressed(out / f"predictions-{step}.npz", **predictions)
295
+ status = {
296
+ "state": "trained" if step == budgets["end"] else "running",
297
+ "step": step,
298
+ "budget": budgets["end"],
299
+ "atomic": metrics["atomic"]["accuracy"],
300
+ "II": metrics["II"]["accuracy"],
301
+ "updated_utc": utc(),
302
+ }
303
+ write_json(out / "status.json", status)
304
+ print(json.dumps(status), flush=True)
305
+
306
+ if not resume:
307
+ checkpoint(0)
308
+ for end in (node for node in nodes if node > start):
309
+ torch.cuda.synchronize()
310
+ t0 = time.perf_counter()
311
+ loss = None
312
+ step = start
313
+ while step < end:
314
+ length = min(256, end - step)
315
+ indices = stream.take(length * spec["batch_size"]).reshape(length, -1)
316
+ atom_count = int((indices < atomic_n).sum())
317
+ counts["atomic"] += atom_count
318
+ counts["composition"] += indices.size - atom_count
319
+ gpu_indices = torch.as_tensor(indices, device=device)
320
+ for j in range(length):
321
+ lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"]))
322
+ loss = graph(gpu_indices[j])
323
+ step += length
324
+ torch.cuda.synchronize()
325
+ seconds += time.perf_counter() - t0
326
+ value = float(loss.detach())
327
+ if not math.isfinite(value):
328
+ raise FloatingPointError(f"Nonfinite loss at {end}")
329
+ checkpoint(end, value)
330
+ start = end
331
+ full_panels = {
332
+ "atomic": arrays["atomic"],
333
+ "atomic_id": arrays["id_atomic"],
334
+ "atomic_ood": arrays["ood_atomic"],
335
+ "II": arrays["test_composite"],
336
+ "OO": arrays["ood_composite"],
337
+ }
338
+ full, predictions = measure(model, full_panels, device)
339
+ full["external_two_calls"] = two_calls(model, panels["II"], device)
340
+ np.savez_compressed(out / "full-predictions.npz", **predictions)
341
+ write_json(
342
+ out / "complete.json",
343
+ {
344
+ "step": start,
345
+ "spec": spec,
346
+ "parameters": metadata["parameters"],
347
+ "training_seconds": seconds,
348
+ "wall_seconds": time.perf_counter() - begun,
349
+ "endpoint": history[-1],
350
+ "full_metrics": full,
351
+ "finished_utc": utc(),
352
+ },
353
+ )
354
+
355
+
356
+ def audit(spec, out):
357
+ """Reload both predeclared comparison checkpoints and independently recount."""
358
+ out = Path(out)
359
+ torch.set_num_threads(1)
360
+ torch.backends.cuda.matmul.allow_tf32 = True
361
+ arrays, panels, data = prepare_world(spec)
362
+ recorded = dict(np.load(out / "world.npz"))
363
+ if array_hash(recorded) != data["dataset_sha256"]:
364
+ raise ValueError("Saved world differs from deterministic reconstruction")
365
+ meta = json.loads((out / "run.json").read_text())
366
+ if meta["world_sha256"] != data["world_sha256"]:
367
+ raise ValueError("World identity mismatch")
368
+ history = json.loads((out / "learning.json").read_text())
369
+ nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"])
370
+ if [record["step"] for record in history] != nodes:
371
+ raise ValueError("Missing or reordered evaluation nodes")
372
+ model, cfg = construct(spec, "cuda:0")
373
+ if sum(p.numel() for p in model.parameters()) != meta["parameters"]:
374
+ raise ValueError("Parameter count mismatch")
375
+ per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True)
376
+ for record in history:
377
+ examples = record["step"] * spec["batch_size"]
378
+ if record["examples"] != examples or examples != (
379
+ record["atomic_examples_seen"] + record["composition_examples_seen"]
380
+ ):
381
+ raise ValueError("Exposure arithmetic mismatch")
382
+ if record["estimated_matmul_training_flops"] != record["step"] * per_step:
383
+ raise ValueError("Executed-shape FLOP mismatch")
384
+ reloaded = []
385
+ for step in sorted(set(budgets.values()) & set(nodes)):
386
+ saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0")
387
+ if saved["spec"] != spec or saved["step"] != step:
388
+ raise ValueError("Checkpoint identity mismatch")
389
+ model.load_state_dict(saved["model"])
390
+ metrics, predictions = measure(model, panels, "cuda:0")
391
+ original = dict(np.load(out / f"predictions-{step}.npz"))
392
+ for key, values in predictions.items():
393
+ if key.endswith("_nll"):
394
+ np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6)
395
+ elif not np.array_equal(values, original[key]):
396
+ raise ValueError(f"Reloaded predictions changed: {step} {key}")
397
+ prior = next(record for record in history if record["step"] == step)["metrics"]
398
+ for name, metric in metrics.items():
399
+ if metric["accuracy"] != prior[name]["accuracy"]:
400
+ raise ValueError("Metric recount mismatch")
401
+ reloaded.append(step)
402
+ full_panels = {
403
+ "atomic": arrays["atomic"],
404
+ "atomic_id": arrays["id_atomic"],
405
+ "atomic_ood": arrays["ood_atomic"],
406
+ "II": arrays["test_composite"],
407
+ "OO": arrays["ood_composite"],
408
+ }
409
+ full, predictions = measure(model, full_panels, "cuda:0")
410
+ original = dict(np.load(out / "full-predictions.npz"))
411
+ for key, value in predictions.items():
412
+ np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6)
413
+ full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0")
414
+ write_json(
415
+ out / "audit.json",
416
+ {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()},
417
+ )
418
+ write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()})
419
+
420
+
421
+ def calibrated_choice(records, thresholds):
422
+ """Development-only success gate; prefer smaller registered model when both pass."""
423
+ candidates = []
424
+ for spec, metrics in records:
425
+ passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items())
426
+ if passed:
427
+ candidates.append(spec)
428
+ return min(candidates, key=lambda spec: spec["layers"]) if candidates else None
429
+
430
+
431
+ def confirmation_specs(config, selected):
432
+ specs = []
433
+ for index, seed in enumerate(config["confirmation_worlds"]):
434
+ for phi in config["support_phi"]:
435
+ specs.append(
436
+ {
437
+ **selected,
438
+ "phase": "confirmation",
439
+ "world_seed": seed,
440
+ "initialization": config["initialization"] + index,
441
+ "stream_seed": config["stream_seed"] + index,
442
+ "name": f"support-w{index + 1}-phi{phi:g}",
443
+ "phi": phi,
444
+ "entities": config["base_spec"]["entities"],
445
+ }
446
+ )
447
+ return specs
448
+
449
+
450
+ def anchors_pass(records, worlds, thresholds):
451
+ """Require exactly the registered independent worlds; no cherry-picked anchors."""
452
+ observed = [spec["world_seed"] for spec, _ in records]
453
+ if len(observed) != len(worlds) or set(observed) != set(worlds):
454
+ return False
455
+ return all(
456
+ all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items())
457
+ for _, metrics in records
458
+ )
459
+
460
+
461
+ def load_specs(config, selected):
462
+ specs = []
463
+ for index, seed in enumerate(config["confirmation_worlds"]):
464
+ for n in config["load_entities"][1:]:
465
+ specs.append(
466
+ {
467
+ **selected,
468
+ "phase": "confirmation",
469
+ "world_seed": seed,
470
+ "initialization": config["initialization"] + index,
471
+ "stream_seed": config["stream_seed"] + index,
472
+ "name": f"load-w{index + 1}-n{n}",
473
+ "phi": config["anchor_phi"],
474
+ "entities": n,
475
+ }
476
+ )
477
+ return specs
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/curve_tracking.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Retry transient W&B connection failures without changing scientific trajectories."""
2
+
3
+ import json
4
+ import time
5
+ import traceback
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ from . import interface_tracking
10
+ from .experiment_tracking import write_json
11
+
12
+
13
+ def utc():
14
+ return datetime.now(timezone.utc).isoformat()
15
+
16
+
17
+ def main():
18
+ import sys
19
+
20
+ root = Path(sys.argv[sys.argv.index("--root") + 1])
21
+ for attempt in range(1, 145):
22
+ try:
23
+ interface_tracking.main()
24
+ return
25
+ except Exception:
26
+ path = root / "tracking-retries.json"
27
+ history = json.loads(path.read_text()) if path.exists() else []
28
+ history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()})
29
+ write_json(path, history)
30
+ print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True)
31
+ time.sleep(min(60, 5 * attempt))
32
+ raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact")
33
+
34
+
35
+ if __name__ == "__main__":
36
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ordinary end-to-end GPT depth and optimization-time development experiment.
2
+
3
+ The frozen random graph is shared across two-, three- and four-hop training.
4
+ Only terminal entities enter composition text; intermediate truth is used for
5
+ evaluation and audit. Existing experimental implementations remain unchanged.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import time
14
+ from dataclasses import replace
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch.nn import functional as F
20
+
21
+ from .bios_model import ModelConfig
22
+ from .grok_depth import EpochStream, make_optimizer, utc, write_json
23
+ from .grok_loop_data import build_world as single_length_world
24
+ from .grok_loop_model import LoopGPT, flops
25
+ from .latent_scaling import model_digest
26
+ from .storage_composition import FullTokenStep, file_hash
27
+ from .storage_frontier import learning_rate
28
+
29
+ BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3
30
+ HOPS = (2, 3, 4)
31
+ TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4")
32
+ EVALUATION_SPLITS = ("atomic",) + tuple(
33
+ f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict")
34
+ )
35
+ DATA_DEFAULTS = {
36
+ "entities": 64,
37
+ "relations": 4,
38
+ "degree": 4,
39
+ "phi": 4.0,
40
+ "id_fraction": 0.75,
41
+ "id_test_fraction": 0.2,
42
+ "evaluation_size": 512,
43
+ }
44
+ SOURCE_FILES = [
45
+ "src/llm_memory_editability/bios_model.py",
46
+ "src/llm_memory_editability/grok_depth.py",
47
+ "src/llm_memory_editability/grok_depth_data.py",
48
+ "src/llm_memory_editability/grok_loop_data.py",
49
+ "src/llm_memory_editability/grok_multihop_data.py",
50
+ "src/llm_memory_editability/grok_loop_model.py",
51
+ "src/llm_memory_editability/latent_scaling.py",
52
+ "src/llm_memory_editability/storage_composition.py",
53
+ "src/llm_memory_editability/storage_frontier.py",
54
+ "src/llm_memory_editability/text_pretrain.py",
55
+ "src/llm_memory_editability/depth_step.py",
56
+ "scripts/run_depth_step.py",
57
+ "tests/test_depth_step.py",
58
+ ]
59
+
60
+
61
+ def data_digest(world):
62
+ digest = hashlib.sha256()
63
+ for name in EVALUATION_SPLITS:
64
+ rows = world[name]
65
+ digest.update(name.encode())
66
+ digest.update(np.asarray(rows.shape, dtype="<i8").tobytes())
67
+ digest.update(rows.astype("<i8", copy=False).tobytes())
68
+ meta = world["metadata"]
69
+ digest.update(
70
+ json.dumps(
71
+ {key: meta[key] for key in ("world_seed", "entities", "relations", "id_mask")},
72
+ sort_keys=True,
73
+ ).encode()
74
+ )
75
+ return digest.hexdigest()
76
+
77
+
78
+ def truth_path_details(world, rows):
79
+ """Return independent truth trajectories and constituent atomic row indices."""
80
+ rows = np.asarray(rows)
81
+ atoms = world["atomic"]
82
+ lookup = {(int(h), int(r)): (index, int(t)) for index, (h, r, t) in enumerate(atoms)}
83
+ if len(lookup) != len(atoms):
84
+ raise ValueError("Duplicate atomic keys")
85
+ if rows.ndim != 2 or rows.shape[1] < 3:
86
+ raise ValueError("Invalid compact truth rows")
87
+ nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64)
88
+ indices = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64)
89
+ nodes[:, 0] = rows[:, 0]
90
+ for i, row in enumerate(rows):
91
+ current = int(row[0])
92
+ for j, relation in enumerate(row[1:-1]):
93
+ edge = lookup.get((current, int(relation)))
94
+ if edge is None:
95
+ raise ValueError("Composition references a missing atomic edge")
96
+ index, current = edge
97
+ indices[i, j], nodes[i, j + 1] = index, current
98
+ if current != int(row[-1]):
99
+ raise ValueError("Composition terminal entity disagrees with graph truth")
100
+ return nodes, indices
101
+
102
+
103
+ def audit_world(world):
104
+ meta = world["metadata"]
105
+ entities, relations = meta["entities"], meta["relations"]
106
+ relation_offset = ENTITY_OFFSET + entities
107
+ id_mask = np.asarray(meta["id_mask"], dtype=bool)
108
+ if id_mask.shape != (len(world["atomic"]),):
109
+ raise ValueError("Invalid atomic ID mask")
110
+ counts = {}
111
+ for name in EVALUATION_SPLITS:
112
+ rows = world[name]
113
+ expected_columns = 3 if name == "atomic" else int(name.rsplit("_", 1)[1]) + 2
114
+ if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != expected_columns:
115
+ raise ValueError("Invalid compact array shape/dtype: " + name)
116
+ if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= relation_offset)):
117
+ raise ValueError("Invalid entity token: " + name)
118
+ if np.any(
119
+ (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations)
120
+ ):
121
+ raise ValueError("Invalid relation token: " + name)
122
+ if len(set(map(tuple, rows[:, :-1]))) != len(rows):
123
+ raise ValueError("Duplicate complete query: " + name)
124
+ _, edges = truth_path_details(world, rows)
125
+ if name.startswith(("train_", "familiar_")) and not id_mask[edges].all():
126
+ raise ValueError("Non-ID fact in familiar training/test: " + name)
127
+ if name.startswith("strict_") and id_mask[edges].any():
128
+ raise ValueError("ID fact in strict composition: " + name)
129
+ counts[name] = len(rows)
130
+ if len(world["atomic"]) != entities * meta["degree"]:
131
+ raise ValueError("Atomic graph degree does not match the contract")
132
+ for hop in HOPS:
133
+ query_sets = [
134
+ set(map(tuple, world[f"{split}_{hop}"][:, :-1]))
135
+ for split in ("train", "familiar", "strict")
136
+ ]
137
+ if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)):
138
+ raise ValueError("Complete query leakage between length-specific splits")
139
+ trained_edges = set()
140
+ for hop in HOPS:
141
+ trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel())
142
+ for hop in HOPS:
143
+ strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel())
144
+ if strict_edges & trained_edges:
145
+ raise ValueError("Strict facts participated in another length's composition training")
146
+ digest = data_digest(world)
147
+ if "dataset_sha256" in meta and meta["dataset_sha256"] != digest:
148
+ raise ValueError("Frozen dataset digest differs from actual arrays")
149
+ return {
150
+ "passed": True,
151
+ "counts": counts,
152
+ "dataset_sha256": digest,
153
+ "truth_edges_independently_traversed": True,
154
+ "complete_query_overlap": 0,
155
+ "all_strict_facts_absent_from_composition_training": True,
156
+ "cross_length_subpath_holdout": False,
157
+ }
158
+
159
+
160
+ def build_world(spec):
161
+ seed = spec.get("world_seed", spec.get("world"))
162
+ if seed is None:
163
+ raise ValueError("A fixed world_seed is required")
164
+ settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()}
165
+ world, shared_atoms, shared_ids = {}, None, None
166
+ source_metadata = {}
167
+ for hop in HOPS:
168
+ original = single_length_world({"world_seed": seed, "hops": hop, **settings})
169
+ # The historical graph reserves only PAD/EOS and uses entity offset 2.
170
+ # Shift every entity/relation token once to reserve the explicit BOS=2.
171
+ atoms = original["atomic"] + 1
172
+ id_set = set(map(tuple, original["id_atomic"]))
173
+ id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool)
174
+ if shared_atoms is None:
175
+ shared_atoms, shared_ids = atoms.copy(), id_mask.copy()
176
+ elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask):
177
+ raise ValueError("Path lengths do not share identical graph and ID mask")
178
+ world[f"train_{hop}"] = original["train_composite"] + 1
179
+ world[f"familiar_{hop}"] = original["test_full_composite"] + 1
180
+ world[f"strict_{hop}"] = original["ood_composite"] + 1
181
+ source_metadata[str(hop)] = original["metadata"]
182
+ world["atomic"] = shared_atoms
183
+ world["metadata"] = {
184
+ "world_seed": int(seed),
185
+ **settings,
186
+ "id_mask": shared_ids.tolist(),
187
+ "source_worlds": source_metadata,
188
+ "same_atomic_and_id_mask_all_lengths": True,
189
+ "source_entity_offset": 2,
190
+ "entity_offset": ENTITY_OFFSET,
191
+ "source_token_shift": 1,
192
+ "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"],
193
+ "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1,
194
+ "evaluation_pools": "Complete test_full_composite and ood_composite",
195
+ "composition_supervision": "Terminal entity only; no intermediate entity",
196
+ "training_objective": "All nonpadding next tokens including EOS",
197
+ "holdout": "Complete queries held out within each length; not subpaths across lengths",
198
+ }
199
+ report = audit_world(world)
200
+ world["metadata"]["dataset_sha256"] = report["dataset_sha256"]
201
+ world["metadata"]["independent_audit"] = report
202
+ expected = spec.get("frozen_data_sha256")
203
+ if expected is not None and expected != report["dataset_sha256"]:
204
+ raise ValueError("Rebuilt data differ from the frozen specification")
205
+ return world
206
+
207
+
208
+ def construct(spec, device):
209
+ if spec.get("context", 9) < 9:
210
+ raise ValueError("Context must support four-hop answer and EOS")
211
+ config = ModelConfig(
212
+ vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1,
213
+ width=spec["width"],
214
+ layers=spec["layers"],
215
+ heads=spec["heads"],
216
+ context=spec.get("context", 9),
217
+ )
218
+ if config.layers > 6:
219
+ raise ValueError("Canonical paired initialization is limited to six unique blocks")
220
+ torch.manual_seed(spec["initialization"])
221
+ canonical = LoopGPT(
222
+ replace(config, layers=6),
223
+ repeats=1,
224
+ dropout=spec.get("dropout", 0.0),
225
+ initialization="scaled_effective",
226
+ )
227
+ model = LoopGPT(
228
+ config,
229
+ repeats=spec["repeats"],
230
+ dropout=spec.get("dropout", 0.0),
231
+ initialization="scaled_effective",
232
+ )
233
+ initial = canonical.state_dict()
234
+ state = {}
235
+ factor = math.sqrt(6 / (config.layers * spec["repeats"]))
236
+ for key in model.state_dict():
237
+ value = initial[key].clone()
238
+ if key.endswith(("attention.proj.weight", "mlp.down.weight")):
239
+ value.mul_(factor)
240
+ state[key] = value
241
+ model.load_state_dict(state)
242
+ return model.to(device)
243
+
244
+
245
+ def prompt_rows(rows, separator=71):
246
+ rows = np.asarray(rows, dtype=np.int64)
247
+ return np.c_[
248
+ np.full(len(rows), BOS, dtype=np.int64),
249
+ rows[:, :-1],
250
+ np.full(len(rows), separator, dtype=np.int64),
251
+ ]
252
+
253
+
254
+ def pack_rows(rows, sequence=8, separator=71):
255
+ """All nonpadding next-token labels; compact rows contain no intermediate nodes."""
256
+ rows = np.asarray(rows, dtype=np.int64)
257
+ sentence = np.c_[
258
+ prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64)
259
+ ]
260
+ length = sentence.shape[1] - 1
261
+ if length > sequence:
262
+ raise ValueError("Packed sequence is too short")
263
+ tokens = np.zeros((len(rows), sequence), dtype=np.int64)
264
+ labels = np.full_like(tokens, -100)
265
+ tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:]
266
+ return tokens, labels
267
+
268
+
269
+ def run_name(spec):
270
+ seed = spec.get("world_seed", spec.get("world"))
271
+ return (
272
+ f"w{seed}-i{spec['initialization']}-d{spec['width']}"
273
+ f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}"
274
+ )
275
+
276
+
277
+ def _mean(values):
278
+ return float(np.asarray(values).mean()) if len(values) else None
279
+
280
+
281
+ @torch.no_grad()
282
+ def generate_rows(model, rows, device, separator=71, batch_size=512):
283
+ """Ordinary full forward, then free tail/EOS generation with answer feedback."""
284
+ rows = np.asarray(rows, dtype=np.int64)
285
+ generated, nll = [], []
286
+ for start in range(0, len(rows), batch_size):
287
+ batch = rows[start : start + batch_size]
288
+ tokens = torch.as_tensor(prompt_rows(batch, separator), device=device)
289
+ first = model(tokens)[:, -1]
290
+ target = torch.as_tensor(batch[:, -1], device=device)
291
+ nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy())
292
+ answer = first.argmax(-1)
293
+ tokens = torch.cat([tokens, answer[:, None]], dim=1)
294
+ stop = model(tokens)[:, -1].argmax(-1)
295
+ generated.append(torch.stack([answer, stop], dim=1).cpu().numpy())
296
+ pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64)
297
+ nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32)
298
+ answer_correct = pred[:, 0] == rows[:, -1]
299
+ correct = answer_correct & (pred[:, 1] == EOS)
300
+ return {
301
+ "n": len(rows),
302
+ "accuracy": _mean(correct),
303
+ "answer_accuracy": _mean(answer_correct),
304
+ "answer_nll": _mean(nll),
305
+ }, {"generated": pred, "correct": correct, "answer_nll": nll}
306
+
307
+
308
+ @torch.no_grad()
309
+ def evaluate(model, world, device):
310
+ before = model.training
311
+ model.eval()
312
+ metrics, predictions = {}, {}
313
+ separator = world["metadata"]["separator_token"]
314
+ try:
315
+ atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator)
316
+ metrics["atomic"] = atomic_metrics
317
+ predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()})
318
+ for name in EVALUATION_SPLITS[1:]:
319
+ rows = world[name]
320
+ task_metrics, direct = generate_rows(model, rows, device, separator)
321
+ nodes, edges = truth_path_details(world, rows)
322
+ coverage = atomic_pred["correct"][edges].all(axis=1)
323
+ current = rows[:, 0].copy()
324
+ hops = rows.shape[1] - 2
325
+ calls = np.empty((len(rows), hops, 2), dtype=np.int64)
326
+ for hop in range(hops):
327
+ query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]]
328
+ _, result = generate_rows(model, query, device, separator)
329
+ calls[:, hop] = result["generated"]
330
+ current = result["generated"][:, 0]
331
+ formats = (calls[:, :, 1] == EOS).all(axis=1)
332
+ autonomous_correct = formats & (current == rows[:, -1])
333
+ path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1)
334
+ task_metrics.update(
335
+ {
336
+ "atomic_correct_coverage": _mean(coverage),
337
+ "conditional_accuracy": _mean(direct["correct"][coverage]),
338
+ "autonomous_two_calls": _mean(autonomous_correct),
339
+ "autonomous_path_accuracy": _mean(path_correct),
340
+ "hop_count": hops,
341
+ }
342
+ )
343
+ metrics[name] = task_metrics
344
+ direct.update(
345
+ {
346
+ "coverage": coverage,
347
+ "autonomous_generated": calls,
348
+ "autonomous_correct": autonomous_correct,
349
+ "autonomous_path_correct": path_correct,
350
+ }
351
+ )
352
+ predictions.update({name + "_" + key: value for key, value in direct.items()})
353
+ finally:
354
+ model.train(before)
355
+ return metrics, predictions
356
+
357
+
358
+ def _validate_spec(spec):
359
+ nodes = spec["nodes"]
360
+ if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]:
361
+ raise ValueError("Nodes must increase from initialization to the fixed endpoint")
362
+ if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set(
363
+ spec["checkpoint_nodes"]
364
+ ):
365
+ raise ValueError("Checkpoint nodes must include initialization and endpoint")
366
+ if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0:
367
+ raise ValueError("The fixed design requires four 32-example streams and dropout zero")
368
+ if spec.get("model_initialization", "scaled_effective") != "scaled_effective":
369
+ raise ValueError("The batch uses scaled_effective residual initialization")
370
+
371
+
372
+ def _save_world(out, world):
373
+ np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS})
374
+ write_json(out / "world-metadata.json", world["metadata"])
375
+
376
+
377
+ def _check_source(source):
378
+ if not source or any(file_hash(path) != digest for path, digest in source.items()):
379
+ raise RuntimeError("Actual source differs from the required frozen source hashes")
380
+
381
+
382
+ def _validate_output(out):
383
+ """Permit scheduler control files while preserving every existing experiment artifact."""
384
+ out = Path(out)
385
+ if out.exists():
386
+ for path in out.iterdir():
387
+ allowed = path.is_file() and (
388
+ path.name == "input-spec.json" or path.name.endswith("-process.log")
389
+ )
390
+ if not allowed:
391
+ raise FileExistsError(
392
+ "Do not overwrite an existing experiment artifact: " + str(path)
393
+ )
394
+
395
+
396
+ def train(spec, out, source, device="cuda:0"):
397
+ _validate_spec(spec)
398
+ _check_source(source)
399
+ if "frozen_data_sha256" not in spec:
400
+ raise ValueError("Training requires frozen_data_sha256")
401
+ out = Path(out)
402
+ _validate_output(out)
403
+ out.mkdir(parents=True, exist_ok=True)
404
+ torch.set_num_threads(1)
405
+ torch.set_num_interop_threads(1)
406
+ torch.cuda.set_device(torch.device(device))
407
+ torch.backends.cuda.matmul.allow_tf32 = True
408
+ torch.backends.cudnn.allow_tf32 = True
409
+ started_process = time.perf_counter()
410
+ world = build_world(spec)
411
+ digest = data_digest(world)
412
+ _save_world(out, world)
413
+ write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest})
414
+ model = construct(spec, device)
415
+ initial_digest = model_digest(model)
416
+ lr = torch.tensor(spec["lr"], device=device)
417
+ optimizer = make_optimizer(model, lr, spec["weight_decay"])
418
+ strata = [world[name] for name in TRAIN_SPLITS]
419
+ sizes = [len(rows) for rows in strata]
420
+ if any(size == 0 for size in sizes):
421
+ raise ValueError("Do not reroll a world with an empty sampled training stratum")
422
+ packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata]
423
+ table = tuple(
424
+ torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True)
425
+ )
426
+ offsets = np.cumsum([0, *sizes[:-1]])
427
+ streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
428
+ counts = [np.zeros(size, dtype=np.int64) for size in sizes]
429
+ graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0))
430
+ flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8)
431
+ token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed)
432
+ history, step, training_seconds = [], 0, 0.0
433
+
434
+ def measure(loss=None):
435
+ metrics, predictions = evaluate(model, world, device)
436
+ row = {
437
+ "step": step,
438
+ "lr": learning_rate(spec, step) if step else 0.0,
439
+ "metrics": metrics,
440
+ "loss": loss,
441
+ "training_seconds": training_seconds,
442
+ "estimated_training_flops": step * flop_step,
443
+ "supervised_tokens": step * token_step,
444
+ "padded_input_tokens": step * spec["batch_size"] * 8,
445
+ }
446
+ history.append(row)
447
+ write_json(out / "learning.json", history)
448
+ np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
449
+ np.savez_compressed(
450
+ out / f"exposures-{step:06d}.npz",
451
+ **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)},
452
+ )
453
+ state = {
454
+ "spec": spec,
455
+ "step": step,
456
+ "model": model.state_dict(),
457
+ "optimizer": optimizer.state_dict(),
458
+ "streams": [s.state_dict() for s in streams],
459
+ "counts": counts,
460
+ "cpu_rng": torch.get_rng_state(),
461
+ "cuda_rng": torch.cuda.get_rng_state(device),
462
+ "source": source,
463
+ "data_sha256": digest,
464
+ }
465
+ torch.save(state, out / "latest.tmp.pt")
466
+ (out / "latest.tmp.pt").replace(out / "latest.pt")
467
+ if step in spec["checkpoint_nodes"]:
468
+ torch.save(
469
+ {"spec": spec, "step": step, "model": model.state_dict()},
470
+ out / f"model-{step:06d}.pt",
471
+ )
472
+ write_json(out / "status.json", {"step": step, "budget": spec["steps"]})
473
+ print(
474
+ json.dumps(
475
+ {
476
+ "run": run_name(spec),
477
+ "step": step,
478
+ "atomic": metrics["atomic"]["accuracy"],
479
+ "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS},
480
+ }
481
+ ),
482
+ flush=True,
483
+ )
484
+ return row
485
+
486
+ measure()
487
+ for end in spec["nodes"][1:]:
488
+ torch.cuda.synchronize()
489
+ started = time.perf_counter()
490
+ while step < end:
491
+ updates = min(128, end - step)
492
+ indices = []
493
+ for i, stream in enumerate(streams):
494
+ draws = stream.take(updates * 32).reshape(updates, 32)
495
+ counts[i] += np.bincount(draws.ravel(), minlength=sizes[i])
496
+ indices.append(draws + offsets[i])
497
+ indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
498
+ for j in range(updates):
499
+ lr.fill_(learning_rate(spec, step + j + 1))
500
+ loss = graph(indices[j])
501
+ step += updates
502
+ torch.cuda.synchronize()
503
+ training_seconds += time.perf_counter() - started
504
+ loss_value = float(loss)
505
+ if not np.isfinite(loss_value):
506
+ raise FloatingPointError("Nonfinite loss at step " + str(step))
507
+ endpoint = measure(loss_value)
508
+ np.savez_compressed(
509
+ out / "exposures.npz",
510
+ **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)},
511
+ )
512
+ result = {
513
+ "spec": spec,
514
+ "source": source,
515
+ "data_sha256": digest,
516
+ "initial_model_sha256": initial_digest,
517
+ "checkpoint_sha256": file_hash(out / "latest.pt"),
518
+ "finished_utc": utc(),
519
+ "parameters": sum(p.numel() for p in model.parameters()),
520
+ "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)),
521
+ "endpoint": endpoint,
522
+ "supervised_tokens": step * token_step,
523
+ "padded_input_tokens": step * spec["batch_size"] * 8,
524
+ "estimated_training_flops": step * flop_step,
525
+ "training_seconds": training_seconds,
526
+ "process_seconds": time.perf_counter() - started_process,
527
+ "environment": {
528
+ "torch": torch.__version__,
529
+ "numpy": np.__version__,
530
+ "cuda": torch.version.cuda,
531
+ "gpu": torch.cuda.get_device_name(device),
532
+ "tf32": True,
533
+ },
534
+ }
535
+ write_json(out / "complete.json", result)
536
+ return result
537
+
538
+
539
+ def compare_metrics(actual, expected):
540
+ if set(actual) != set(expected):
541
+ raise AssertionError("Metric task keys differ")
542
+ for task, values in actual.items():
543
+ if set(values) != set(expected[task]):
544
+ raise AssertionError("Metric field keys differ")
545
+ for key, value in values.items():
546
+ if key == "answer_nll" and value is not None:
547
+ np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5)
548
+ elif value != expected[task][key]:
549
+ raise AssertionError(f"Saved metric differs: {task}.{key}")
550
+
551
+
552
+ def compare_predictions(actual, path):
553
+ maximum = 0.0
554
+ with np.load(path) as saved:
555
+ if set(actual) != set(saved.files):
556
+ raise AssertionError("Prediction keys differ")
557
+ for key, value in actual.items():
558
+ if key.endswith("answer_nll"):
559
+ np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5)
560
+ if value.size:
561
+ maximum = max(maximum, float(np.abs(value - saved[key]).max()))
562
+ else:
563
+ np.testing.assert_array_equal(value, saved[key])
564
+ return maximum
565
+
566
+
567
+ def audit(out, device="cuda:0"):
568
+ out = Path(out)
569
+ torch.set_num_threads(1)
570
+ torch.set_num_interop_threads(1)
571
+ torch.cuda.set_device(torch.device(device))
572
+ torch.backends.cuda.matmul.allow_tf32 = True
573
+ torch.backends.cudnn.allow_tf32 = True
574
+ result = json.loads((out / "complete.json").read_text())
575
+ recorded = json.loads((out / "spec.json").read_text())
576
+ source, spec = result["source"], result["spec"]
577
+ _check_source(source)
578
+ _validate_spec(spec)
579
+ if recorded["spec"] != spec or recorded["source"] != source:
580
+ raise AssertionError("Recorded specification/source differ")
581
+ if file_hash(out / "latest.pt") != result["checkpoint_sha256"]:
582
+ raise AssertionError("Latest checkpoint hash differs")
583
+ world = build_world(spec)
584
+ digest = data_digest(world)
585
+ if digest != result["data_sha256"] or digest != recorded["data_sha256"]:
586
+ raise AssertionError("Rebuilt data differ from records")
587
+ if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]:
588
+ raise AssertionError("Archived world metadata differ")
589
+ with np.load(out / "world.npz") as archived:
590
+ if set(archived.files) != set(EVALUATION_SPLITS):
591
+ raise AssertionError("Archived world keys differ")
592
+ for name in EVALUATION_SPLITS:
593
+ np.testing.assert_array_equal(archived[name], world[name])
594
+ model = construct(spec, device)
595
+ if model_digest(model) != result["initial_model_sha256"]:
596
+ raise AssertionError("Paired initialization differs")
597
+ history = json.loads((out / "learning.json").read_text())
598
+ if [row["step"] for row in history] != spec["nodes"]:
599
+ raise AssertionError("Recorded learning nodes differ")
600
+ by_node = {row["step"]: row for row in history}
601
+ if by_node[spec["steps"]] != result["endpoint"]:
602
+ raise AssertionError("Endpoint differs from the learning curve")
603
+ maximum = 0.0
604
+ for node in spec["checkpoint_nodes"]:
605
+ checkpoint = torch.load(
606
+ out / f"model-{node:06d}.pt", map_location=device, weights_only=False
607
+ )
608
+ if checkpoint["spec"] != spec or checkpoint["step"] != node:
609
+ raise AssertionError("Checkpoint specification/node differ")
610
+ model.load_state_dict(checkpoint["model"])
611
+ metrics, predictions = evaluate(model, world, device)
612
+ compare_metrics(metrics, by_node[node]["metrics"])
613
+ maximum = max(
614
+ maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz")
615
+ )
616
+ saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
617
+ if (
618
+ saved["spec"] != spec
619
+ or saved["source"] != source
620
+ or saved["step"] != spec["steps"]
621
+ or saved["data_sha256"] != digest
622
+ ):
623
+ raise AssertionError("Latest state identity differs")
624
+ sizes = [len(world[name]) for name in TRAIN_SPLITS]
625
+ streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
626
+ counts = [np.zeros(size, dtype=np.int64) for size in sizes]
627
+ previous = 0
628
+ for node in spec["nodes"]:
629
+ for i, stream in enumerate(streams):
630
+ draws = (
631
+ stream.take((node - previous) * 32)
632
+ if node > previous
633
+ else np.empty(0, dtype=np.int64)
634
+ )
635
+ counts[i] += np.bincount(draws, minlength=sizes[i])
636
+ with np.load(out / f"exposures-{node:06d}.npz") as actual:
637
+ for name, count in zip(TRAIN_SPLITS, counts, strict=True):
638
+ np.testing.assert_array_equal(actual[name], count)
639
+ previous = node
640
+ with np.load(out / "exposures.npz") as actual:
641
+ for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)):
642
+ np.testing.assert_array_equal(actual[name], count)
643
+ np.testing.assert_array_equal(saved["counts"][i], count)
644
+ if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1:
645
+ raise AssertionError("EpochStream actual exposures are unbalanced")
646
+ stream = EpochStream(sizes[i], spec["stream_seed"] + i)
647
+ stream.load_state_dict(saved["streams"][i])
648
+ np.testing.assert_array_equal(stream.take(32), streams[i].take(32))
649
+ model.load_state_dict(saved["model"])
650
+ metrics, predictions = evaluate(model, world, device)
651
+ compare_metrics(metrics, result["endpoint"]["metrics"])
652
+ maximum = max(
653
+ maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz")
654
+ )
655
+ checked = {
656
+ "passed": True,
657
+ "dataset_rebuilt_and_archived_exact": True,
658
+ "initial_model_exact": True,
659
+ "checkpoint_nodes": spec["checkpoint_nodes"],
660
+ "endpoint_tokens_exact": True,
661
+ "all_nodes_exposure_counters_exact": True,
662
+ "stream_state_continuation_exact": True,
663
+ "max_nll_difference": maximum,
664
+ "nll_rtol": 1e-5,
665
+ "nll_atol": 1e-5,
666
+ "utc": utc(),
667
+ }
668
+ write_json(out / "audit.json", checked)
669
+ return checked
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Answer-only MLP editing calibration with frozen parent-logit regularization.
2
+
3
+ This development grid changes the editor objective and learning rate, preserving
4
+ the completed v1 experiment. KL on a finite replay set is a regularizer, not an
5
+ exact preservation constraint. Kdev checks the operation; U never selects it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import hashlib
12
+ import json
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torch.nn import functional as F
19
+
20
+ from .depth_step import EOS, pack_rows
21
+ from .depth_step import SOURCE_FILES as TRAIN_SOURCES
22
+ from .depth_step_mechanism import edit_cases, generate
23
+ from .grok_depth import utc, write_json
24
+ from .latent_scaling import model_digest
25
+ from .storage_composition import file_hash
26
+
27
+ SOURCE_FILES = list(
28
+ dict.fromkeys(
29
+ [
30
+ *TRAIN_SOURCES,
31
+ "src/llm_memory_editability/depth_step_mechanism.py",
32
+ "src/llm_memory_editability/depth_step_edit_calibration.py",
33
+ "scripts/calibrate_depth_step_edit.py",
34
+ "tests/test_depth_step_edit_calibration.py",
35
+ ]
36
+ )
37
+ )
38
+ PARAMETER = "blocks.0.mlp.down.weight"
39
+ NODES = (0, 20, 100, 200)
40
+ LEARNING_RATES = (0.0001, 0.001, 0.003)
41
+
42
+
43
+ def _array_hash(array):
44
+ array = np.asarray(array)
45
+ digest = hashlib.sha256(str(array.dtype).encode())
46
+ digest.update(np.asarray(array.shape, dtype="<i8").tobytes())
47
+ digest.update(array.tobytes())
48
+ return digest.hexdigest()
49
+
50
+
51
+ def calibration_cases(world, n_cases=2, replay_n=32, keep_n=32, total_cases=8):
52
+ """Partition fixed cases without consulting a checkpoint or any predictions."""
53
+ all_cases = edit_cases(world, n_facts=total_cases, replay_n=replay_n)
54
+ if not 0 < n_cases <= total_cases:
55
+ raise ValueError("Invalid calibration-case prefix")
56
+ atoms = world["atomic"]
57
+ order = sorted(range(len(atoms)), key=lambda index: tuple(atoms[index]))
58
+ for case in all_cases[:n_cases]:
59
+ successor_rows = set(map(tuple, case["tasks"]["necessary_successor_atomic"]))
60
+ successor_indices = {i for i, row in enumerate(atoms) if tuple(row) in successor_rows}
61
+ excluded = {case["atomic_index"], *case["replay_indices"], *successor_indices}
62
+ keep_indices = [i for i in order if i not in excluded][:keep_n]
63
+ if len(keep_indices) != keep_n:
64
+ raise ValueError("Insufficient development keep atoms")
65
+ case["keep_dev_indices"] = keep_indices
66
+ case["tasks"]["Kdev_atomic"] = atoms[keep_indices].copy()
67
+ excluded_u = {case["atomic_index"], *case["replay_indices"], *keep_indices}
68
+ unused = [i for i in range(len(atoms)) if i not in excluded_u]
69
+ case["unused_atomic_indices"] = unused
70
+ case["tasks"]["U_atomic"] = atoms[unused].copy()
71
+ return all_cases[:n_cases], [case["atomic_index"] for case in all_cases[n_cases:]]
72
+
73
+
74
+ def answer_eos_batch(rows, world, device):
75
+ """Select only SEP->answer and teacher-forced answer->EOS supervision."""
76
+ rows = np.asarray(rows, dtype=np.int64)
77
+ tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"])
78
+ positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1))
79
+ batch_indices = np.arange(len(rows))[:, None]
80
+ selected = labels[batch_indices, positions]
81
+ if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]):
82
+ raise ValueError("Answer/EOS positions disagree with the packed sequence")
83
+ return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected))
84
+
85
+
86
+ def answer_eos_logits(model, batch):
87
+ tokens, positions, _labels = batch
88
+ return model(tokens, positions=positions)
89
+
90
+
91
+ def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities):
92
+ """CE only on two factual-output tokens; KL(parent || edited), equally weighted."""
93
+ if parent_log_probabilities.requires_grad:
94
+ raise ValueError("Parent logits must be detached")
95
+ target_logits = answer_eos_logits(model, target_batch)
96
+ ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten())
97
+ replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1)
98
+ kl = F.kl_div(
99
+ replay_log.flatten(0, 1),
100
+ parent_log_probabilities.flatten(0, 1),
101
+ reduction="batchmean",
102
+ log_target=True,
103
+ )
104
+ return ce + kl, ce, kl
105
+
106
+
107
+ def _measure(model, case, world, device, step):
108
+ metrics, raw = {}, {}
109
+ for name, rows in case["tasks"].items():
110
+ values, predictions = generate(model, rows, world, device)
111
+ if name in case["original_d_rows"]:
112
+ original = case["original_d_rows"][name]
113
+ changed = rows[:, -1] != original[:, -1]
114
+ predicted = predictions["predictions"]
115
+ correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS)
116
+ old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS)
117
+ values.update(
118
+ {
119
+ "changed_answer_n": int(changed.sum()),
120
+ "changed_answer_coverage": float(changed.mean()) if len(rows) else None,
121
+ "changed_answer_accuracy": float(correct[changed].mean())
122
+ if changed.any()
123
+ else None,
124
+ "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None,
125
+ }
126
+ )
127
+ metrics[name] = values
128
+ raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()})
129
+ return metrics, raw
130
+
131
+
132
+ def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES):
133
+ """One independently initialized branch, with fixed parent KL reference."""
134
+ if arm not in {"edit", "review"}:
135
+ raise ValueError("Arm must be edit or review")
136
+ if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0:
137
+ raise ValueError("Nodes must increase from zero")
138
+ parent_hash = model_digest(model)
139
+ edited = copy.deepcopy(model).eval()
140
+ for name, parameter in edited.named_parameters():
141
+ parameter.requires_grad_(name == PARAMETER)
142
+ parameter.grad = None
143
+ before = {name: value.detach().clone() for name, value in edited.state_dict().items()}
144
+ parameter = dict(edited.named_parameters())[PARAMETER]
145
+ optimizer = torch.optim.Adam([parameter], lr=lr)
146
+ target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]])
147
+ target_batch = answer_eos_batch(target_rows, world, device)
148
+ replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device)
149
+ with torch.no_grad():
150
+ parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach()
151
+ raw = {
152
+ "parent_replay_log_probabilities": parent_log.cpu().numpy(),
153
+ "replay_teacherforced_labels": replay_batch[2].cpu().numpy(),
154
+ }
155
+ for name, old_rows in case["original_d_rows"].items():
156
+ raw[name + "_original_rows"] = old_rows
157
+ raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1]
158
+ step, history, loss_values = 0, [], None
159
+ for node in nodes:
160
+ while step < node:
161
+ optimizer.zero_grad(set_to_none=True)
162
+ loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log)
163
+ loss.backward()
164
+ optimizer.step()
165
+ step += 1
166
+ loss_values = {
167
+ "total": float(loss.detach()),
168
+ "target_ce": float(ce.detach()),
169
+ "replay_kl": float(kl.detach()),
170
+ }
171
+ metrics, predictions = _measure(edited, case, world, device, step)
172
+ raw.update(predictions)
173
+ target_name = "E_new" if arm == "edit" else "E_old"
174
+ keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95
175
+ target_pass = metrics[target_name]["accuracy"] == 1.0
176
+ history.append(
177
+ {
178
+ "step": step,
179
+ "loss": loss_values,
180
+ "metrics": metrics,
181
+ "Kdev_at_least_95_percent": keep_pass,
182
+ "target_atomic_success": target_pass,
183
+ "calibration_operation_pass": keep_pass and target_pass,
184
+ }
185
+ )
186
+ changed = [
187
+ name for name, value in edited.state_dict().items() if not torch.equal(value, before[name])
188
+ ]
189
+ if set(changed) - {PARAMETER}:
190
+ raise ValueError("A frozen state tensor changed")
191
+ if model_digest(model) != parent_hash:
192
+ raise ValueError("Original checkpoint model changed")
193
+ delta = parameter.detach() - before[PARAMETER]
194
+ raw["mlp_down_weight_delta"] = delta.cpu().numpy()
195
+ record = {
196
+ "arm": arm,
197
+ "lr": lr,
198
+ "atomic_index": case["atomic_index"],
199
+ "old_fact": case["old_fact"],
200
+ "new_fact": case["new_fact"],
201
+ "replay_indices": case["replay_indices"],
202
+ "keep_dev_indices": case["keep_dev_indices"],
203
+ "unused_atomic_indices": case["unused_atomic_indices"],
204
+ "parent_model_sha256": parent_hash,
205
+ "final_model_sha256": model_digest(edited),
206
+ "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()),
207
+ "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()),
208
+ "updated_parameter": PARAMETER,
209
+ "changed_state_tensors": changed,
210
+ "weight_delta_l2": float(delta.norm()),
211
+ "history": history,
212
+ }
213
+ return record, raw
214
+
215
+
216
+ def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2):
217
+ """Freeze data, all arms, sources, and initial weights before any model inference."""
218
+ out = Path(out)
219
+ out.mkdir(parents=True, exist_ok=False)
220
+ if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates):
221
+ raise ValueError("Invalid learning rate")
222
+ cases, remaining = calibration_cases(world, n_cases=n_cases)
223
+ serialized = []
224
+ for case in cases:
225
+ entry = {
226
+ key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}
227
+ }
228
+ entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()}
229
+ entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()}
230
+ entry["original_d_rows"] = {
231
+ key: value.tolist() for key, value in case["original_d_rows"].items()
232
+ }
233
+ serialized.append(entry)
234
+ config = {
235
+ "phase": "development_calibration",
236
+ "created_utc": utc(),
237
+ "source_checkpoint": source,
238
+ "source": {path: file_hash(path) for path in SOURCE_FILES},
239
+ "parent_model_sha256": model_digest(model),
240
+ "initial_down_weight_sha256": _array_hash(
241
+ model.blocks[0].mlp.down.weight.detach().cpu().numpy()
242
+ ),
243
+ "learning_rates": list(learning_rates),
244
+ "nodes": list(NODES),
245
+ "cases": serialized,
246
+ "n_cases": n_cases,
247
+ "matrix": [
248
+ {"case": i, "lr": lr, "arm": arm}
249
+ for i in range(n_cases)
250
+ for lr in learning_rates
251
+ for arm in ("edit", "review")
252
+ ],
253
+ "reserved_original_case_indices": remaining,
254
+ "reserved_cases_are_independent_world_confirmation": False,
255
+ "optimizer": "Adam, no weight decay",
256
+ "parameter": PARAMETER,
257
+ "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits",
258
+ "replay_kl_weight": 1.0,
259
+ "supervised_prefix_tokens": 0,
260
+ "trained_compositions": 0,
261
+ "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors",
262
+ "Kdev_threshold": 0.95,
263
+ "U_selection": "All remaining atomic facts, including unused necessary successors",
264
+ "U_or_D_select_editor": False,
265
+ "all_grid_failures_retained": True,
266
+ "executions_affected_by_shared_edit": model.repeats,
267
+ "limits": [
268
+ "Finite replay KL is not strict output preservation",
269
+ "A successful Kdev check does not establish unobserved U preservation",
270
+ "Cases share one development world and original checkpoints",
271
+ ],
272
+ }
273
+ write_json(out / "calibration-config.json", config)
274
+ return config, cases
275
+
276
+
277
+ def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2):
278
+ """Validate an existing prepared configuration, without rewriting it."""
279
+ out = Path(out)
280
+ config_file = out / "calibration-config.json"
281
+ config = json.loads(config_file.read_text())
282
+ if any(path.name != config_file.name for path in out.iterdir()):
283
+ raise FileExistsError("Existing branch artifacts prevent a repeated execution")
284
+ if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases:
285
+ raise ValueError("Requested grid differs from prepared calibration")
286
+ expected_source = config["source_checkpoint"]
287
+ for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"):
288
+ if source[key] != expected_source[key]:
289
+ raise ValueError("Checkpoint or data differ from prepared calibration: " + key)
290
+ if model_digest(model) != config["parent_model_sha256"]:
291
+ raise ValueError("Parent parameter hash differs from prepared calibration")
292
+ expected_matrix = [
293
+ {"case": i, "lr": lr, "arm": arm}
294
+ for i in range(n_cases)
295
+ for lr in learning_rates
296
+ for arm in ("edit", "review")
297
+ ]
298
+ if config["matrix"] != expected_matrix or config["nodes"] != list(NODES):
299
+ raise ValueError("Prepared update matrix or nodes changed")
300
+ if (
301
+ config["parameter"] != PARAMETER
302
+ or config["replay_kl_weight"] != 1.0
303
+ or config["Kdev_threshold"] != 0.95
304
+ or config["U_or_D_select_editor"]
305
+ ):
306
+ raise ValueError("Prepared operation contract changed")
307
+ cases, remaining = calibration_cases(world, n_cases=n_cases)
308
+ if remaining != config["reserved_original_case_indices"]:
309
+ raise ValueError("Reserved cases changed")
310
+ for case, frozen in zip(cases, config["cases"], strict=True):
311
+ for key in (
312
+ "atomic_index",
313
+ "old_fact",
314
+ "new_fact",
315
+ "replay_indices",
316
+ "keep_dev_indices",
317
+ "unused_atomic_indices",
318
+ "propagation_scope",
319
+ ):
320
+ if case[key] != frozen[key]:
321
+ raise ValueError("Case selection changed: " + key)
322
+ if set(case["tasks"]) != set(frozen["task_rows"]):
323
+ raise ValueError("Prepared task set changed")
324
+ for name, rows in case["tasks"].items():
325
+ if (
326
+ rows.tolist() != frozen["task_rows"][name]
327
+ or _array_hash(rows) != frozen["task_sha256"][name]
328
+ ):
329
+ raise ValueError("Prepared task rows changed: " + name)
330
+ for name, rows in case["original_d_rows"].items():
331
+ if rows.tolist() != frozen["original_d_rows"][name]:
332
+ raise ValueError("Prepared original D labels changed")
333
+ for path, expected in config["source"].items():
334
+ if file_hash(path) != expected:
335
+ raise ValueError("Source changed after calibration freeze: " + path)
336
+ return config, cases
337
+
338
+
339
+ def execute_calibration(model, world, config, cases, out, device):
340
+ out = Path(out)
341
+ if model_digest(model) != config["parent_model_sha256"]:
342
+ raise ValueError("Parent parameter hash differs from frozen configuration")
343
+ for path, expected in config["source"].items():
344
+ if file_hash(path) != expected:
345
+ raise ValueError("Source changed after calibration freeze: " + path)
346
+ for case, expected in zip(cases, config["cases"], strict=True):
347
+ for name, rows in case["tasks"].items():
348
+ if _array_hash(rows) != expected["task_sha256"][name]:
349
+ raise ValueError("Task rows changed after freeze: " + name)
350
+ started = time.perf_counter()
351
+ records = []
352
+ for item in config["matrix"]:
353
+ number, lr, arm = item["case"], item["lr"], item["arm"]
354
+ record, raw = calibrated_edit_one(
355
+ model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"])
356
+ )
357
+ label = f"case{number:02d}-lr{lr:.4f}-{arm}"
358
+ np.savez_compressed(out / (label + "-raw.npz"), **raw)
359
+ write_json(out / (label + ".json"), record)
360
+ records.append(record)
361
+ print(f"Calibration branch completed: {label}", flush=True)
362
+ report = {
363
+ "phase": "development_calibration",
364
+ "records": records,
365
+ "config_sha256": file_hash(out / "calibration-config.json"),
366
+ "completed_branches": len(records),
367
+ "wall_seconds": time.perf_counter() - started,
368
+ "model_selection_by_U_or_D": False,
369
+ }
370
+ write_json(out / "calibration-summary.json", report)
371
+ return report
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Descriptive entity readouts, pure-first-hop interventions and MLP edits.
2
+
3
+ No fitted probe or performance predictor is used. Residual readouts and raw MLP
4
+ cosines are descriptions; only interventions test a causal contribution. The
5
+ truth graph chooses queries, donors and edits before any model is evaluated.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import json
12
+ import math
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torch.nn import functional as F
19
+
20
+ from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details
21
+ from .grok_depth import utc, write_json
22
+ from .storage_composition import file_hash
23
+
24
+
25
+ def traced_forward(model, tokens, patches=None):
26
+ """Use the real SDPA computation and record every executed block/position.
27
+
28
+ Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position)
29
+ to a batch of replacement vectors. Repeated executions of a shared block
30
+ remain separately indexed. Attention maps are descriptive manual softmax;
31
+ the forward uses the same SDPA primitive as LoopGPT.
32
+ """
33
+ if model.training:
34
+ raise ValueError("Tracing requires evaluation mode")
35
+ patches = patches or {}
36
+ length = tokens.shape[1]
37
+ x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device))
38
+ cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")}
39
+ consumed = set()
40
+ for index, block in enumerate(model.iter_blocks()):
41
+ z = block.ln1(x)
42
+ batch, _, width = z.shape
43
+ a = block.attention
44
+ q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
45
+ q, k, v = (part.transpose(1, 2) for part in (q, k, v))
46
+ scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads)
47
+ causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril()
48
+ attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1)
49
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0)
50
+ attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width))
51
+ x = x + attention_delta
52
+ mlp_delta = block.mlp(block.ln2(x))
53
+ for key, replacement in patches.items():
54
+ layer, component, position = key
55
+ if layer == index and component == "mlp_delta":
56
+ if replacement.shape != mlp_delta[:, position].shape:
57
+ raise ValueError("Patch shape differs from selected MLP position")
58
+ mlp_delta = mlp_delta.clone()
59
+ mlp_delta[:, position] = replacement
60
+ consumed.add(key)
61
+ x = x + mlp_delta
62
+ for key, replacement in patches.items():
63
+ layer, component, position = key
64
+ if layer == index and component == "postresidual":
65
+ if replacement.shape != x[:, position].shape:
66
+ raise ValueError("Patch shape differs from selected residual position")
67
+ x = x.clone()
68
+ x[:, position] = replacement
69
+ consumed.add(key)
70
+ for key, value in (
71
+ ("attention_map", attention_map),
72
+ ("attention_delta", attention_delta),
73
+ ("mlp_delta", mlp_delta),
74
+ ("postresidual", x),
75
+ ):
76
+ cache[key].append(value.detach())
77
+ if consumed != set(patches):
78
+ raise ValueError("Unknown execution/component in patch")
79
+ logits = F.linear(model.ln_final(x), model.token.weight)
80
+ return logits, {key: torch.stack(values) for key, values in cache.items()}
81
+
82
+
83
+ def _separator(world):
84
+ return int(world["metadata"]["separator_token"])
85
+
86
+
87
+ def _mean(values):
88
+ return float(np.mean(values)) if len(values) else None
89
+
90
+
91
+ @torch.no_grad()
92
+ def generate(model, rows, world, device, batch_size=256):
93
+ """Free answer then free EOS, retaining full-vocabulary probabilities."""
94
+ rows = np.asarray(rows, dtype=np.int64)
95
+ predictions, probabilities, gold_probabilities = [], [], []
96
+ for begin in range(0, len(rows), batch_size):
97
+ selected = rows[begin : begin + batch_size]
98
+ tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device)
99
+ probability = model(tokens)[:, -1].softmax(-1)
100
+ answer = probability.argmax(-1)
101
+ eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1)
102
+ predictions.append(torch.stack((answer, eos), 1).cpu().numpy())
103
+ probabilities.append(probability.cpu().numpy())
104
+ gold_probabilities.append(
105
+ probability[
106
+ torch.arange(len(selected), device=device),
107
+ torch.as_tensor(selected[:, -1], device=device),
108
+ ]
109
+ .cpu()
110
+ .numpy()
111
+ )
112
+ vocab = model.config.vocab_size
113
+ predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64)
114
+ prob = (
115
+ np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32)
116
+ )
117
+ gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0)
118
+ correct = predicted[:, 0] == rows[:, -1]
119
+ return {
120
+ "n": len(rows),
121
+ "answer_accuracy": _mean(correct),
122
+ "accuracy": _mean(correct & (predicted[:, 1] == EOS)),
123
+ "gold_probability": _mean(gold_prob),
124
+ }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob}
125
+
126
+
127
+ def select_donors(world, rows):
128
+ """Lexicographic donors know exactly one fact and no target second relation."""
129
+ atoms = world["atomic"]
130
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
131
+ order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i]))
132
+ nodes, _ = truth_path_details(world, rows)
133
+ same, changed, changed_tail = [], [], []
134
+ for row, path in zip(rows, nodes, strict=True):
135
+ h, r1, r2, old_tail = map(int, row)
136
+ bridge = int(path[1])
137
+ identical = next(
138
+ (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1
139
+ )
140
+ different = next(
141
+ (
142
+ i
143
+ for i in order
144
+ if int(atoms[i, 2]) != bridge
145
+ and (int(atoms[i, 2]), r2) in lookup
146
+ and lookup[(int(atoms[i, 2]), r2)] != old_tail
147
+ ),
148
+ -1,
149
+ )
150
+ same.append(identical)
151
+ changed.append(different)
152
+ changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1)
153
+ return {
154
+ "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64),
155
+ "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64),
156
+ "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64),
157
+ }
158
+
159
+
160
+ @torch.no_grad()
161
+ def entity_readouts(model, cache, targets, entities):
162
+ """Apply the unmodified final norm/tied readout; raw MLP cosine is separate."""
163
+ residual = cache["postresidual"]
164
+ logits = F.linear(model.ln_final(residual), model.token.weight)
165
+ entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities]
166
+ probabilities = logits.softmax(-1)
167
+ entity_probabilities = entity_logits.softmax(-1)
168
+ embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1)
169
+ cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T
170
+ arrays = {}
171
+ for name, token_ids in targets.items():
172
+ ids = torch.as_tensor(token_ids, device=residual.device)
173
+ full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1)
174
+ entity_ids = full_ids - ENTITY_OFFSET
175
+ gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1)
176
+ gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1)
177
+ arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1)
178
+ arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze(
179
+ -1
180
+ )
181
+ arrays[name + "_residual_entity_probability"] = entity_probabilities.gather(
182
+ -1, entity_ids
183
+ ).squeeze(-1)
184
+ arrays[name + "_mlp_embedding_cosine"] = gold_cosine
185
+ arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1)
186
+ return {name: value.cpu().numpy() for name, value in arrays.items()}
187
+
188
+
189
+ @torch.no_grad()
190
+ def _patched_generation(model, tokens, patch):
191
+ logits, _ = traced_forward(model, tokens, patch)
192
+ probability = logits[:, -1].softmax(-1)
193
+ answer = probability.argmax(-1)
194
+ # Reapply the same intervention while freely generating the EOS token.
195
+ extended = torch.cat((tokens, answer[:, None]), dim=1)
196
+ eos_logits, _ = traced_forward(model, extended, patch)
197
+ eos = eos_logits[:, -1].argmax(-1)
198
+ return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy()
199
+
200
+
201
+ def trace_analysis(model, world, out, device, max_queries=128):
202
+ out = Path(out)
203
+ out.mkdir(parents=True, exist_ok=False)
204
+ model.eval()
205
+ started = time.perf_counter()
206
+ raw, baseline = {}, {}
207
+ for split in ("atomic", "familiar_2", "strict_2"):
208
+ metrics, prediction = generate(model, world[split], world, device)
209
+ baseline[split] = metrics
210
+ raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()})
211
+ indices = np.arange(min(max_queries, len(world["familiar_2"])))
212
+ rows = world["familiar_2"][indices]
213
+ nodes, edges = truth_path_details(world, rows)
214
+ tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device)
215
+ with torch.no_grad():
216
+ reference = model(tokens)
217
+ actual, cache = traced_forward(model, tokens)
218
+ difference = float((actual - reference).abs().max())
219
+ torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6)
220
+ if not torch.equal(actual.argmax(-1), reference.argmax(-1)):
221
+ raise ValueError("Traced forward changes full-vocabulary argmax")
222
+ raw.update(
223
+ {
224
+ "query_indices": indices,
225
+ "query_rows": rows,
226
+ "truth_nodes": nodes,
227
+ "truth_atomic_indices": edges,
228
+ }
229
+ )
230
+ raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()})
231
+ raw.update(
232
+ entity_readouts(
233
+ model,
234
+ cache,
235
+ {"bridge": nodes[:, 1], "tail": nodes[:, -1]},
236
+ world["metadata"]["entities"],
237
+ )
238
+ )
239
+ donors = select_donors(world, rows)
240
+ raw.update(donors)
241
+ atom_predictions = raw["baseline_atomic_predictions"]
242
+ atoms = world["atomic"]
243
+ atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS)
244
+ atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)}
245
+ raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1)
246
+ records = []
247
+ for style in ("self", "same_bridge", "different_bridge"):
248
+ donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"]
249
+ valid = donor_ids >= 0
250
+ selected = np.flatnonzero(valid)
251
+ if not len(selected):
252
+ continue
253
+ donor_rows = world["atomic"][donor_ids[valid]]
254
+ donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device)
255
+ with torch.no_grad():
256
+ _, donor_cache = traced_forward(model, donor_tokens)
257
+ expected = (
258
+ donors["different_bridge_tail"][valid]
259
+ if style == "different_bridge"
260
+ else rows[valid, -1]
261
+ )
262
+ new_second_indices = np.asarray(
263
+ [
264
+ atomic_key_indices[(int(donor[2]), int(query[2]))]
265
+ for donor, query in zip(donor_rows, rows[valid], strict=True)
266
+ ]
267
+ )
268
+ premises = (
269
+ atom_correct[edges[valid]].all(1)
270
+ & atom_correct[donor_ids[valid]]
271
+ & atom_correct[new_second_indices]
272
+ )
273
+ raw[style + "_premises_correct"] = premises
274
+ for layer in range(model.effective_depth):
275
+ for component in ("mlp_delta", "postresidual"):
276
+ for position in (2, 1):
277
+ key = f"{style}_layer{layer}_{component}_pos{position}"
278
+ patch = {
279
+ (layer, component, position): donor_cache[component][layer, :, position]
280
+ }
281
+ prediction, probability = _patched_generation(model, tokens[valid], patch)
282
+ raw[key + "_selected_query_indices"] = selected
283
+ raw[key + "_predictions"] = prediction
284
+ raw[key + "_answer_probabilities"] = probability
285
+ following = prediction[:, 0] == expected
286
+ correct = prediction[:, 0] == rows[valid, -1]
287
+ base_pred = raw["baseline_familiar_2_predictions"][indices[valid]]
288
+ base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS)
289
+ if style == "self" and not np.array_equal(prediction, base_pred):
290
+ raise ValueError("Pure-first-hop self patch changes generation")
291
+ record = {
292
+ "donor": style,
293
+ "execution": layer,
294
+ "component": component,
295
+ "position": position,
296
+ "n": len(selected),
297
+ "selected_query_coverage": len(selected) / len(rows),
298
+ "full_pool_coverage": len(selected) / len(world["familiar_2"]),
299
+ "new_route_answer_accuracy": _mean(following),
300
+ "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)),
301
+ "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)),
302
+ "baseline_correct_coverage": _mean(base_correct),
303
+ "all_required_atomic_correct_coverage": _mean(premises),
304
+ "new_route_conditional_on_required_atomics": _mean(
305
+ (following & (prediction[:, 1] == EOS))[premises]
306
+ ),
307
+ "new_route_conditional_on_baseline_correct": _mean(
308
+ (following & (prediction[:, 1] == EOS))[base_correct]
309
+ ),
310
+ }
311
+ records.append(record)
312
+ with torch.no_grad():
313
+ entity_embedding = model.token.weight[
314
+ ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"]
315
+ ]
316
+ normalized = F.normalize(entity_embedding, dim=-1)
317
+ raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy()
318
+ raw["entity_embedding_singular_values"] = (
319
+ torch.linalg.svdvals(entity_embedding).cpu().numpy()
320
+ )
321
+ np.savez_compressed(out / "trace-raw.npz", **raw)
322
+ report = {
323
+ "phase": "development",
324
+ "created_utc": utc(),
325
+ "baseline": baseline,
326
+ "query_selection": (
327
+ "First 128 familiar_2 rows in frozen data order, independent of predictions"
328
+ ),
329
+ "selected_queries": len(rows),
330
+ "full_pool_queries": len(world["familiar_2"]),
331
+ "selection_coverage": len(rows) / len(world["familiar_2"]),
332
+ "forward_max_absolute_difference": difference,
333
+ "forward_all_argmax_identical": True,
334
+ "donor_information": (
335
+ "Only BOS, head, first relation, SEP; no second relation or final answer"
336
+ ),
337
+ "patch_position_roles": {"1": "head control", "2": "first relation"},
338
+ "interventions": records,
339
+ "wall_seconds": time.perf_counter() - started,
340
+ "limits": [
341
+ "Unfitted final-norm tied readout and raw cosine are descriptive",
342
+ "Attention maps are descriptive; patch tests entire state or MLP contribution",
343
+ "Layers, positions and queries are dependent measurements in one world",
344
+ ],
345
+ }
346
+ write_json(out / "trace-summary.json", report)
347
+ return report
348
+
349
+
350
+ def edit_cases(world, n_facts=8, replay_n=32):
351
+ """Choose graph-based first-hop edits before observing any model behavior."""
352
+ atoms = world["atomic"]
353
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
354
+ candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]}
355
+ order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i]))
356
+ cases = []
357
+ for index in order:
358
+ h, relation, old_bridge = map(int, atoms[index])
359
+ if (h, relation) not in candidate_first:
360
+ continue
361
+ first_rows = world["familiar_2"][
362
+ (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation)
363
+ ]
364
+ bridges = sorted({int(t) for _, _, t in atoms})
365
+ new_bridge = next(
366
+ (
367
+ b
368
+ for b in bridges
369
+ if b != old_bridge
370
+ and all(
371
+ (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1])
372
+ for row in first_rows
373
+ )
374
+ ),
375
+ None,
376
+ )
377
+ if new_bridge is None:
378
+ continue
379
+ replay_indices = np.asarray([i for i in order if i != index][:replay_n])
380
+ if len(replay_indices) != replay_n:
381
+ raise ValueError("Insufficient nonedited replay atoms")
382
+ new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64)
383
+ old_fact = atoms[index : index + 1].copy()
384
+ edited_lookup = {**lookup, (h, relation): new_bridge}
385
+ tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()}
386
+ original_d_rows = {}
387
+ unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices]
388
+ tasks["U_atomic"] = atoms[unreplayed].copy()
389
+ successor_keys = set()
390
+ for split in ("familiar_2", "strict_2"):
391
+ rows = world[split]
392
+ nodes, path_indices = truth_path_details(world, rows)
393
+ first = path_indices[:, 0] == index
394
+ second = (path_indices[:, 1] == index) & ~first
395
+ unaffected = ~(first | second)
396
+ for role, mask in (("first", first), ("second", second)):
397
+ changed = rows[mask].copy()
398
+ for i, row in enumerate(changed):
399
+ bridge = edited_lookup[(int(row[0]), int(row[1]))]
400
+ changed[i, -1] = edited_lookup[(bridge, int(row[2]))]
401
+ if role == "first" and (bridge, int(row[2])) != (h, relation):
402
+ successor_keys.add((bridge, int(row[2])))
403
+ tasks[f"D_{role}_{split}"] = changed
404
+ original_d_rows[f"D_{role}_{split}"] = rows[mask].copy()
405
+ tasks["U_" + split] = rows[unaffected].copy()
406
+ # All facts occurring as either hop in U retain their graph labels.
407
+ if index in path_indices[unaffected]:
408
+ raise ValueError("Edited fact leaked into the unaffected holdout")
409
+ del nodes
410
+ successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys]
411
+ tasks["necessary_successor_atomic"] = atoms[successor_indices].copy()
412
+ cases.append(
413
+ {
414
+ "atomic_index": index,
415
+ "old_fact": old_fact[0].tolist(),
416
+ "new_fact": new_fact[0].tolist(),
417
+ "replay_indices": replay_indices.tolist(),
418
+ "tasks": tasks,
419
+ "original_d_rows": original_d_rows,
420
+ "propagation_scope": {
421
+ name: {
422
+ "n": len(old_rows),
423
+ "changed_answer_n": int(
424
+ np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1])
425
+ ),
426
+ "source_pool_n": len(world[name.split("_", 2)[2]]),
427
+ }
428
+ for name, old_rows in original_d_rows.items()
429
+ },
430
+ }
431
+ )
432
+ if len(cases) == n_facts:
433
+ break
434
+ if len(cases) != n_facts:
435
+ raise ValueError("Fewer graph-valid fixed edit cases than requested")
436
+ return cases
437
+
438
+
439
+ def _atomic_loss(model, rows, world, device):
440
+ tokens, labels = pack_rows(rows, separator=_separator(world))
441
+ tokens = torch.as_tensor(tokens, device=device)
442
+ labels = torch.as_tensor(labels, device=device)
443
+ logits = model(tokens)
444
+ return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
445
+
446
+
447
+ def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01):
448
+ """Independently edit one checkpoint; only unique block-0 MLP down changes."""
449
+ if arm not in {"edit", "review"}:
450
+ raise ValueError("Arm must be edit or review")
451
+ if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0:
452
+ raise ValueError("Nodes must be increasing with initial measurement")
453
+ edited = copy.deepcopy(model).eval()
454
+ target_name = "blocks.0.mlp.down.weight"
455
+ for name, parameter in edited.named_parameters():
456
+ parameter.requires_grad_(name == target_name)
457
+ parameter.grad = None
458
+ before = {name: value.detach().clone() for name, value in edited.state_dict().items()}
459
+ parameter = dict(edited.named_parameters())[target_name]
460
+ optimizer = torch.optim.Adam([parameter], lr=lr)
461
+ objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]])
462
+ history, raw = [], {}
463
+ for name, old_rows in case["original_d_rows"].items():
464
+ raw[name + "_original_rows"] = old_rows
465
+ raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1]
466
+ step = 0
467
+ final_loss = None
468
+ for node in nodes:
469
+ while step < node:
470
+ optimizer.zero_grad(set_to_none=True)
471
+ loss = 0.5 * _atomic_loss(edited, objective_rows, world, device)
472
+ loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device)
473
+ loss.backward()
474
+ optimizer.step()
475
+ step += 1
476
+ final_loss = float(loss.detach())
477
+ measures = {}
478
+ for name, rows in case["tasks"].items():
479
+ metrics, prediction = generate(edited, rows, world, device)
480
+ if name in case["original_d_rows"]:
481
+ old_rows = case["original_d_rows"][name]
482
+ changed_mask = rows[:, -1] != old_rows[:, -1]
483
+ predicted = prediction["predictions"]
484
+ correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS)
485
+ old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS)
486
+ metrics.update(
487
+ {
488
+ "changed_answer_n": int(changed_mask.sum()),
489
+ "changed_answer_coverage": _mean(changed_mask),
490
+ "changed_answer_accuracy": _mean(correct[changed_mask]),
491
+ "old_answer_accuracy": _mean(old_correct),
492
+ }
493
+ )
494
+ measures[name] = metrics
495
+ raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()})
496
+ history.append({"step": step, "loss": final_loss, "metrics": measures})
497
+ changed = [
498
+ name for name, value in edited.state_dict().items() if not torch.equal(value, before[name])
499
+ ]
500
+ if set(changed) - {target_name}:
501
+ raise ValueError("Parameters outside the frozen MLP projection changed")
502
+ delta = parameter.detach() - before[target_name]
503
+ raw["mlp_down_weight_delta"] = delta.cpu().numpy()
504
+ return {
505
+ "arm": arm,
506
+ "atomic_index": case["atomic_index"],
507
+ "old_fact": case["old_fact"],
508
+ "new_fact": case["new_fact"],
509
+ "replay_indices": case["replay_indices"],
510
+ "propagation_scope": case["propagation_scope"],
511
+ "updated_parameter": target_name,
512
+ "changed_state_tensors": changed,
513
+ "weight_delta_l2": float(delta.norm()),
514
+ "history": history,
515
+ }, raw
516
+
517
+
518
+ def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01):
519
+ out = Path(out)
520
+ out.mkdir(parents=True, exist_ok=False)
521
+ started = time.perf_counter()
522
+ cases = edit_cases(world, n_facts=n_facts)
523
+ serializable_cases = [
524
+ {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}}
525
+ | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}}
526
+ for case in cases
527
+ ]
528
+ # This is written before evaluating or updating any case.
529
+ write_json(out / "data-selected-edit-cases.json", serializable_cases)
530
+ records = []
531
+ for number, case in enumerate(cases):
532
+ for arm in ("edit", "review"):
533
+ record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr)
534
+ np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw)
535
+ write_json(out / f"case{number:02d}-{arm}.json", record)
536
+ records.append(record)
537
+ report = {
538
+ "phase": "development",
539
+ "created_utc": utc(),
540
+ "n_facts": n_facts,
541
+ "nodes": list(nodes),
542
+ "lr": lr,
543
+ "optimizer": "Adam, no weight decay",
544
+ "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE",
545
+ "trained_compositions": 0,
546
+ "unique_block_edited": 0,
547
+ "executions_affected_by_shared_edit": model.repeats,
548
+ "independent_layers": len(model.blocks),
549
+ "execution_depth": model.effective_depth,
550
+ "scope_difference": (
551
+ "Loop block-0 update applies at every repeat; ordinary block-0 applies once"
552
+ ),
553
+ "records": records,
554
+ "wall_seconds": time.perf_counter() - started,
555
+ "limits": [
556
+ "Edits use the same fixed budget; failed target changes remain in results",
557
+ "MLP-only parameter fine-tuning is not a constrained-preservation theorem",
558
+ "Each case independently starts from the same checkpoint",
559
+ "A single development world is not independent confirmation",
560
+ ],
561
+ }
562
+ write_json(out / "edit-summary.json", report)
563
+ return report
564
+
565
+
566
+ def load_run(run_dir, checkpoint, device):
567
+ run_dir, checkpoint = Path(run_dir), Path(checkpoint)
568
+ saved = torch.load(checkpoint, map_location=device, weights_only=False)
569
+ model = construct(saved["spec"], device).eval()
570
+ model.load_state_dict(saved["model"], strict=True)
571
+ arrays = np.load(run_dir / "world.npz", allow_pickle=False)
572
+ world = {key: arrays[key] for key in arrays.files}
573
+ world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text())
574
+ from .depth_step import audit_world
575
+
576
+ audit = audit_world(world)
577
+ if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]):
578
+ raise ValueError("Checkpoint and archived data digest disagree")
579
+ return (
580
+ model,
581
+ world,
582
+ {
583
+ "checkpoint": str(checkpoint),
584
+ "checkpoint_sha256": file_hash(checkpoint),
585
+ "step": saved["step"],
586
+ "spec": saved["spec"],
587
+ "dataset_sha256": audit["dataset_sha256"],
588
+ },
589
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiment_tracking.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """W&B sidecar for future experiments; reads trainer artifacts without changing training."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fcntl
7
+ import hashlib
8
+ import importlib
9
+ import json
10
+ import math
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json"
18
+ PRIVATE_KEYS = {
19
+ "api_key",
20
+ "wandb_api_key",
21
+ "access_token",
22
+ "auth_token",
23
+ "password",
24
+ "credentials",
25
+ "secret",
26
+ }
27
+
28
+
29
+ def read_json(path):
30
+ return json.loads(Path(path).read_text())
31
+
32
+
33
+ def write_json(path, value):
34
+ path = Path(path)
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ temp = path.with_suffix(".tmp")
37
+ temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
38
+ temp.replace(path)
39
+
40
+
41
+ def public_config(value):
42
+ if isinstance(value, dict):
43
+ return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS}
44
+ if isinstance(value, list):
45
+ return [public_config(v) for v in value]
46
+ return value
47
+
48
+
49
+ def numeric_fields(value, prefix):
50
+ result = {}
51
+ for key, item in value.items():
52
+ name = f"{prefix}/{key}"
53
+ if isinstance(item, dict):
54
+ result.update(numeric_fields(item, name))
55
+ elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item):
56
+ result[name] = item
57
+ return result
58
+
59
+
60
+ def learning_metrics(record, previous=None):
61
+ """Keep the actual optimizer step and task denominators; derive interval throughput."""
62
+ result = {"training/step": int(record["step"])}
63
+ result.update(numeric_fields(record.get("metrics", {}), "eval"))
64
+ groups = {
65
+ "training_seconds": "perf/training_seconds",
66
+ "wall_seconds": "perf/wall_seconds",
67
+ "examples": "exposure/examples",
68
+ "supervised_tokens": "exposure/supervised_tokens",
69
+ "executed_input_tokens": "compute/executed_input_tokens",
70
+ "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops",
71
+ "atomic_epochs": "exposure/atomic_epochs",
72
+ "composition_epochs": "exposure/composition_epochs",
73
+ }
74
+ for key, value in record.items():
75
+ if key in {"step", "metrics"}:
76
+ continue
77
+ if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value):
78
+ result[groups.get(key, f"training/{key}")] = value
79
+ if previous is not None and record["step"] > previous["step"]:
80
+ steps = record["step"] - previous["step"]
81
+ if "training_seconds" in record and "training_seconds" in previous:
82
+ seconds = record["training_seconds"] - previous["training_seconds"]
83
+ if seconds > 0:
84
+ result["perf/training_ms_per_update"] = 1000 * seconds / steps
85
+ result["perf/updates_per_second"] = steps / seconds
86
+ if "examples" in record and "examples" in previous:
87
+ result["perf/examples_per_second"] = (
88
+ record["examples"] - previous["examples"]
89
+ ) / seconds
90
+ return result
91
+
92
+
93
+ class ArtifactRunTracker:
94
+ def __init__(self, sdk, batch, path, settings):
95
+ self.path = Path(path)
96
+ self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json"
97
+ self.metadata = read_json(self.path / "run.json")
98
+ self.settings = settings
99
+ identity = {
100
+ "batch": Path(batch).name,
101
+ "name": self.path.name,
102
+ "spec": public_config(self.metadata.get("spec", {})),
103
+ "world_sha256": self.metadata.get("world_sha256"),
104
+ "initial_model_sha256": self.metadata.get("initial_model_sha256"),
105
+ }
106
+ fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
107
+ saved = read_json(self.state_path) if self.state_path.exists() else {}
108
+ if saved:
109
+ assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed"
110
+ assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"]
111
+ self.state = {
112
+ "run_id": fingerprint[:16],
113
+ "fingerprint": fingerprint,
114
+ "entity": settings["entity"],
115
+ "project": settings["project"],
116
+ "last_logged_step": -1,
117
+ **saved,
118
+ }
119
+ options = {"disable_git": True}
120
+ if not settings["system_metrics"]:
121
+ options["x_disable_stats"] = True
122
+ else:
123
+ if "gpu" in self.metadata:
124
+ options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],)
125
+ if "pid" in self.metadata:
126
+ options["x_stats_pid"] = self.metadata["pid"]
127
+ mode = settings["mode"]
128
+ run_id = self.state["run_id"]
129
+ if mode == "offline" and saved:
130
+ segment = saved.get("offline_segment", 0) + 1
131
+ self.state["offline_segment"] = segment
132
+ run_id = f"{run_id[:12]}{segment:04x}"
133
+ self.state_path.parent.mkdir(parents=True, exist_ok=True)
134
+ config = {
135
+ **identity,
136
+ "scientific_run_id": self.state["run_id"],
137
+ **{
138
+ k: self.metadata[k]
139
+ for k in [
140
+ "model",
141
+ "phase",
142
+ "evaluation_nodes",
143
+ "execution_lock_sha256",
144
+ "parameters",
145
+ "vocab_size",
146
+ "atomic_examples",
147
+ "composition_examples",
148
+ "dtype",
149
+ "gpu_name",
150
+ ]
151
+ if k in self.metadata
152
+ },
153
+ }
154
+ self.run = sdk.init(
155
+ entity=settings["entity"],
156
+ project=settings["project"],
157
+ group=self.metadata.get("tracking_group", Path(batch).name),
158
+ name=self.path.name,
159
+ id=run_id,
160
+ config=config,
161
+ mode=mode,
162
+ resume="allow" if mode == "online" else None,
163
+ job_type=self.metadata.get("job_type", "training"),
164
+ tags=self.metadata.get("tags", []),
165
+ dir=str(self.state_path.parent),
166
+ save_code=False,
167
+ reinit="create_new",
168
+ settings=sdk.Settings(**options),
169
+ )
170
+ self.run.define_metric("training/step")
171
+ self.run.define_metric("*", step_metric="training/step")
172
+ if mode == "online":
173
+ # The public history is authoritative: an SDK restart can briefly report step 0,
174
+ # and a local cursor can include points queued before a network interruption.
175
+ remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}")
176
+ self.cursor = remote.lastHistoryStep
177
+ else:
178
+ self.cursor = self.state["last_logged_step"]
179
+ self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id)
180
+ write_json(self.state_path, self.state)
181
+
182
+ def poll(self):
183
+ history = read_json(self.path / "learning.json")
184
+ previous = None
185
+ for record in history:
186
+ step = int(record["step"])
187
+ if step > self.cursor:
188
+ self.run.log(learning_metrics(record, previous), step=step)
189
+ self.cursor = step
190
+ self.state["last_logged_step"] = step
191
+ write_json(self.state_path, self.state)
192
+ previous = record
193
+ status_path = self.path / "status.json"
194
+ if status_path.exists():
195
+ status = read_json(status_path)
196
+ self.run.summary["training_state"] = status.get("state", "unknown")
197
+ complete = (self.path / "complete.json").exists()
198
+ failure_record = (self.path / "failure.json").exists() or (
199
+ self.path / "failure-detail.json"
200
+ ).exists()
201
+ failed = failure_record and not complete
202
+ self.run.summary["has_failure_record"] = failure_record
203
+ self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists()
204
+ if complete or failed:
205
+ self.run.summary["scientific_final_step"] = self.cursor
206
+ self.run.finish(exit_code=1 if failed else 0)
207
+ return True
208
+ return False
209
+
210
+ def close(self):
211
+ self.run.finish()
212
+
213
+
214
+ def main():
215
+ parser = argparse.ArgumentParser(description=__doc__)
216
+ parser.add_argument("--root", type=Path, required=True)
217
+ parser.add_argument("--runs-dir", type=Path)
218
+ parser.add_argument("--defaults", type=Path, default=DEFAULTS)
219
+ parser.add_argument("--entity")
220
+ parser.add_argument("--project")
221
+ parser.add_argument("--mode", choices=["online", "offline"])
222
+ parser.add_argument("--once", action="store_true")
223
+ parser.add_argument("--detach", action="store_true")
224
+ args = parser.parse_args()
225
+ settings = read_json(args.defaults)
226
+ for name in ["entity", "project", "mode"]:
227
+ settings[name] = (
228
+ getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name]
229
+ )
230
+ if not settings["enabled"]:
231
+ raise SystemExit("Experiment tracking is disabled in the selected defaults")
232
+ local = args.root / "tracking-wandb"
233
+ local.mkdir(parents=True, exist_ok=True)
234
+ if args.detach:
235
+ metadata_path = local / "process.json"
236
+ if metadata_path.exists():
237
+ pid = read_json(metadata_path)["pid"]
238
+ try:
239
+ os.kill(pid, 0)
240
+ except ProcessLookupError:
241
+ pass
242
+ else:
243
+ raise SystemExit(f"Tracking process already running: {pid}")
244
+ arguments = [a for a in sys.argv[1:] if a != "--detach"]
245
+ command = [
246
+ sys.executable,
247
+ "-u",
248
+ "-m",
249
+ "llm_memory_editability.experiment_tracking",
250
+ *arguments,
251
+ ]
252
+ with (local / "tracker.log").open("a") as log:
253
+ process = subprocess.Popen(
254
+ command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True
255
+ )
256
+ write_json(metadata_path, {"pid": process.pid, "command": command})
257
+ print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")}))
258
+ return
259
+ try:
260
+ sdk = importlib.import_module("wandb")
261
+ except ImportError as error:
262
+ raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error
263
+ with (local / "tracker.lock").open("w") as lock:
264
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
265
+ active, finished = {}, set()
266
+ runs_dir = args.runs_dir or args.root / "development"
267
+ try:
268
+ while True:
269
+ for path in sorted(runs_dir.glob("*")):
270
+ if path in active or path in finished:
271
+ continue
272
+ if not (path / "run.json").exists() or not (path / "learning.json").exists():
273
+ continue
274
+ active[path] = ArtifactRunTracker(sdk, args.root, path, settings)
275
+ print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True)
276
+ for path, tracker in list(active.items()):
277
+ current = read_json(path / "run.json")
278
+ if current.get("pid") != tracker.metadata.get("pid"):
279
+ tracker.close()
280
+ tracker = ArtifactRunTracker(sdk, args.root, path, settings)
281
+ active[path] = tracker
282
+ if tracker.poll():
283
+ finished.add(path)
284
+ del active[path]
285
+ if args.once:
286
+ break
287
+ manifest = args.root / "controller-state.json"
288
+ if manifest.exists() and not active:
289
+ if read_json(manifest).get("state") in {"complete", "finished_with_failures"}:
290
+ break
291
+ time.sleep(settings["poll_seconds"])
292
+ finally:
293
+ for tracker in active.values():
294
+ tracker.close()
295
+
296
+
297
+ if __name__ == "__main__":
298
+ main()
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiments.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic analytical illustration from the supplied research memo."""
2
+
3
+ import platform
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+
8
+ from .low_rank import evaluate_update
9
+
10
+
11
+ def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]:
12
+ """Compare a shared-rule update with a one-entry exception.
13
+
14
+ At rank budget one, both changes have rank-one deltas but only the rule's
15
+ target is representable. At budget two, both targets are representable.
16
+ This is a classical matrix fact, not evidence of LLM editing difficulty.
17
+ """
18
+ original = np.ones((2, 2), dtype=float)
19
+ cases = {
20
+ "original": evaluate_update(original, original, rank, atol),
21
+ "rule": evaluate_update(original, 2 * original, rank, atol),
22
+ "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol),
23
+ }
24
+ return {
25
+ "experiment": "minimal_low_rank",
26
+ "scope": (
27
+ "Analytical SVD illustration for fully observed real matrices with a "
28
+ "fixed total rank budget and unweighted Frobenius error. No training, "
29
+ "optimization path, or Transformer editing is evaluated. Numerical "
30
+ "rank counts singular values greater than an absolute tolerance; "
31
+ "this example does not validate the broader research hypothesis."
32
+ ),
33
+ "parameters": {
34
+ "rank_budget": cases["original"]["rank_budget"],
35
+ "atol": cases["original"]["atol"],
36
+ },
37
+ "versions": {"python": platform.python_version(), "numpy": np.__version__},
38
+ "cases": cases,
39
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024).
2
+
3
+ Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c.
4
+ The compact vocabulary, widths and data sizes are explicit experimental adaptations.
5
+ CUDA Graph capture is an execution optimization, not a change to the training objective.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import time
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch.nn import functional as F
21
+
22
+ from .bios_model import CausalLM, ModelConfig, matmul_flops
23
+
24
+
25
+ def utc():
26
+ return datetime.now(timezone.utc).isoformat()
27
+
28
+
29
+ def write_json(path, value):
30
+ path = Path(path)
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ tmp = path.with_suffix(path.suffix + ".tmp")
33
+ tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
34
+ tmp.replace(path)
35
+
36
+
37
+ class SmallGPT(CausalLM):
38
+ """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout."""
39
+
40
+ def __init__(self, config, dropout=0.1):
41
+ super().__init__(config)
42
+ self.dropout = dropout
43
+
44
+ def forward(self, tokens, positions=None):
45
+ p = self.dropout if self.training else 0.0
46
+ x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
47
+ x = F.dropout(x, p=p, training=self.training)
48
+ for block in self.blocks:
49
+ z = block.ln1(x)
50
+ batch, length, width = z.shape
51
+ a = block.attention
52
+ q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
53
+ y = F.scaled_dot_product_attention(
54
+ q.transpose(1, 2),
55
+ k.transpose(1, 2),
56
+ v.transpose(1, 2),
57
+ is_causal=True,
58
+ dropout_p=p,
59
+ )
60
+ y = a.proj(y.transpose(1, 2).reshape(batch, length, width))
61
+ x = x + F.dropout(y, p=p, training=self.training)
62
+ x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training)
63
+ x = self.ln_final(x)
64
+ if positions is not None:
65
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
66
+ return F.linear(x, self.token.weight)
67
+
68
+
69
+ def pack_rows(rows):
70
+ """Right-pad; supervise tail and EOS only. No BOS or answer delimiter."""
71
+ rows = np.asarray(rows, dtype=np.int64)
72
+ x = np.zeros((len(rows), 4), dtype=np.int64)
73
+ x[:, : rows.shape[1]] = rows
74
+ positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1))
75
+ labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)]
76
+ return x, positions, labels
77
+
78
+
79
+ def make_optimizer(model, lr, weight_decay):
80
+ decay = [p for p in model.parameters() if p.ndim >= 2]
81
+ no_decay = [p for p in model.parameters() if p.ndim < 2]
82
+ return torch.optim.AdamW(
83
+ [
84
+ {"params": decay, "weight_decay": weight_decay},
85
+ {"params": no_decay, "weight_decay": 0.0},
86
+ ],
87
+ lr=lr,
88
+ betas=(0.9, 0.999),
89
+ eps=1e-8,
90
+ fused=True,
91
+ capturable=True,
92
+ )
93
+
94
+
95
+ class GraphStep:
96
+ """Capture complete AdamW step and undo warmup without rebinding state tensors."""
97
+
98
+ def __init__(self, model, optimizer, table, batch_size, clip=1.0):
99
+ self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device)
100
+ self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip
101
+ weights = {k: v.detach().clone() for k, v in model.state_dict().items()}
102
+ state = {
103
+ p: {
104
+ k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v)
105
+ for k, v in s.items()
106
+ }
107
+ for p, s in optimizer.state.items()
108
+ }
109
+ cpu_rng = torch.get_rng_state()
110
+ cuda_rng = torch.cuda.get_rng_state(table[0].device)
111
+ torch.cuda.synchronize()
112
+ stream = torch.cuda.Stream()
113
+ stream.wait_stream(torch.cuda.current_stream())
114
+ with torch.cuda.stream(stream):
115
+ for _ in range(3):
116
+ self.eager()
117
+ torch.cuda.current_stream().wait_stream(stream)
118
+ torch.cuda.synchronize()
119
+ self.graph = torch.cuda.CUDAGraph()
120
+ with torch.cuda.graph(self.graph):
121
+ self.loss, self.grad_norm = self.eager()
122
+ torch.cuda.synchronize()
123
+ with torch.no_grad():
124
+ for k, v in model.state_dict().items():
125
+ v.copy_(weights[k])
126
+ for param, values in optimizer.state.items():
127
+ before = state.get(param, {})
128
+ for k, v in values.items():
129
+ if torch.is_tensor(v):
130
+ if k in before:
131
+ v.copy_(before[k])
132
+ else:
133
+ v.zero_()
134
+ for p in model.parameters():
135
+ if p.grad is not None:
136
+ p.grad.zero_()
137
+ torch.set_rng_state(cpu_rng)
138
+ torch.cuda.set_rng_state(cuda_rng, table[0].device)
139
+
140
+ def eager(self):
141
+ self.optimizer.zero_grad(set_to_none=False)
142
+ x, pos, labels = (t[self.index] for t in self.table)
143
+ logits = self.model(x, positions=pos)
144
+ loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten())
145
+ loss.backward()
146
+ norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
147
+ self.optimizer.step()
148
+ return loss, norm
149
+
150
+ def __call__(self, indices):
151
+ self.index.copy_(indices)
152
+ self.graph.replay()
153
+ return self.loss
154
+
155
+
156
+ class EpochStream:
157
+ """Uniform shuffled epochs of the combined atomic/composite training set."""
158
+
159
+ def __init__(self, size, seed):
160
+ self.size = size
161
+ self.rng = np.random.default_rng(seed)
162
+ self.remaining = np.empty(0, dtype=np.int64)
163
+
164
+ def take(self, n):
165
+ parts = []
166
+ while n:
167
+ if not len(self.remaining):
168
+ self.remaining = self.rng.permutation(self.size)
169
+ count = min(n, len(self.remaining))
170
+ parts.append(self.remaining[:count])
171
+ self.remaining = self.remaining[count:]
172
+ n -= count
173
+ return np.concatenate(parts)
174
+
175
+ def state_dict(self):
176
+ return {
177
+ "size": self.size,
178
+ "rng": self.rng.bit_generator.state,
179
+ "remaining": self.remaining.copy(),
180
+ }
181
+
182
+ def load_state_dict(self, state):
183
+ assert state["size"] == self.size
184
+ self.rng.bit_generator.state = state["rng"]
185
+ self.remaining = state["remaining"].copy()
186
+
187
+
188
+ @torch.no_grad()
189
+ def evaluate_rows(model, rows, device, batch_size=1024):
190
+ model.eval()
191
+ packed = pack_rows(rows)
192
+ answers, stops, losses = [], [], []
193
+ for start in range(0, len(rows), batch_size):
194
+ x, pos, labels = (
195
+ torch.as_tensor(t[start : start + batch_size], device=device) for t in packed
196
+ )
197
+ logits = model(x, pos)
198
+ losses.append(
199
+ F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none")
200
+ .view(-1, 2)
201
+ .cpu()
202
+ .numpy()
203
+ )
204
+ answer = logits[:, 0].argmax(-1)
205
+ # Actual generated answer is fed back when producing EOS.
206
+ x[torch.arange(len(x), device=device), pos[:, 1]] = answer
207
+ stop = model(x, pos)[:, 1].argmax(-1)
208
+ answers.append(answer.cpu().numpy())
209
+ stops.append(stop.cpu().numpy())
210
+ model.train()
211
+ if not len(rows):
212
+ return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {}
213
+ answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses)
214
+ correct = answer == rows[:, -1]
215
+ return {
216
+ "n": len(rows),
217
+ "answer_accuracy": float(correct.mean()),
218
+ "accuracy": float((correct & (stop == 1)).mean()),
219
+ "nll": float(nll.mean()),
220
+ }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]}
221
+
222
+
223
+ @torch.no_grad()
224
+ def two_calls(model, rows, device):
225
+ if not len(rows):
226
+ return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}
227
+ first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)]
228
+ _, first_pred = evaluate_rows(model, first, device)
229
+ second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]]
230
+ result, second_pred = evaluate_rows(model, second, device)
231
+ result["accuracy"] = float(
232
+ (
233
+ (second_pred["answer"] == rows[:, -1])
234
+ & (second_pred["stop"] == 1)
235
+ & (first_pred["stop"] == 1)
236
+ ).mean()
237
+ )
238
+ return result
239
+
240
+
241
+ def source_hash(paths):
242
+ return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths}
243
+
244
+
245
+ def run(spec, world, out, device="cuda:0", resume=False):
246
+ """Run a fixed scientific budget. Intermediate evaluations never change training."""
247
+ out = Path(out)
248
+ out.mkdir(parents=True, exist_ok=True)
249
+ torch.set_num_threads(1)
250
+ torch.set_num_interop_threads(1)
251
+ torch.backends.cuda.matmul.allow_tf32 = True
252
+ torch.backends.cudnn.allow_tf32 = True
253
+ torch.manual_seed(spec["initialization"])
254
+ torch.cuda.manual_seed_all(spec["initialization"])
255
+ device = torch.device(device)
256
+ torch.cuda.set_device(device)
257
+ cfg = ModelConfig(
258
+ vocab_size=2 + spec["entities"] + spec["relations"],
259
+ width=spec["width"],
260
+ layers=spec["layers"],
261
+ heads=spec["heads"],
262
+ context=8,
263
+ )
264
+ model = SmallGPT(cfg, spec["dropout"]).to(device)
265
+ lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device)
266
+ opt = make_optimizer(model, lr, spec["weight_decay"])
267
+ atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"])
268
+ table = tuple(
269
+ torch.as_tensor(np.concatenate([a, c]), device=device)
270
+ for a, c in zip(atoms, comps, strict=True)
271
+ )
272
+ stream = EpochStream(len(table[0]), spec["stream_seed"])
273
+ counts = {"atomic": 0, "composite": 0}
274
+ elapsed_training, elapsed_eval = 0.0, 0.0
275
+ start_step = 0
276
+ checkpoint = out / "latest.pt"
277
+ if resume:
278
+ state = torch.load(checkpoint, map_location=device, weights_only=False)
279
+ assert state["spec"] == spec
280
+ model.load_state_dict(state["model"])
281
+ opt.load_state_dict(state["optimizer"])
282
+ # load_state_dict replaces the LR tensor; retain the optimizer's live tensor.
283
+ lr = opt.param_groups[0]["lr"]
284
+ for group in opt.param_groups:
285
+ group["lr"] = lr
286
+ stream.load_state_dict(state["stream"])
287
+ counts = state["counts"]
288
+ elapsed_training = state["elapsed_training"]
289
+ elapsed_eval = state["elapsed_eval"]
290
+ start_step = state["step"]
291
+ torch.set_rng_state(state["cpu_rng"].cpu())
292
+ torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
293
+ started = time.perf_counter()
294
+ graph = GraphStep(model, opt, table, spec["batch_size"])
295
+ capture_seconds = time.perf_counter() - started
296
+ names = ("atomic", "train_composite", "test_composite", "ood_composite")
297
+ nparams = sum(p.numel() for p in model.parameters())
298
+ flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2)
299
+ rows_log = []
300
+ if (out / "learning.json").exists():
301
+ rows_log = json.loads((out / "learning.json").read_text())
302
+ if resume:
303
+ # A crash can leave a log newer than the atomically replaced checkpoint.
304
+ rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values())
305
+ rows_log.sort(key=lambda r: r["step"])
306
+ if start_step == spec["steps"]:
307
+ endpoint = rows_log[-1]
308
+ write_json(
309
+ out / "complete.json",
310
+ {
311
+ "finished_utc": utc(),
312
+ "spec": spec,
313
+ "parameters": nparams,
314
+ "training_seconds": elapsed_training,
315
+ "evaluation_seconds": elapsed_eval,
316
+ "endpoint": endpoint,
317
+ "completion_recovered_from_final_checkpoint": True,
318
+ },
319
+ )
320
+ write_json(
321
+ out / "status.json",
322
+ {
323
+ "state": "complete",
324
+ "step": start_step,
325
+ "budget": spec["steps"],
326
+ "updated_utc": utc(),
327
+ "atomic": endpoint["atomic"]["accuracy"],
328
+ "train": endpoint["train_composite"]["accuracy"],
329
+ "test": endpoint["test_composite"]["accuracy"],
330
+ },
331
+ )
332
+ return rows_log[-1]
333
+
334
+ def measure(step, last_loss=None):
335
+ nonlocal elapsed_eval
336
+ torch.cuda.synchronize()
337
+ t0 = time.perf_counter()
338
+ row = {
339
+ "step": step,
340
+ "utc": utc(),
341
+ "parameters": nparams,
342
+ "training_seconds": elapsed_training,
343
+ "capture_seconds": capture_seconds,
344
+ "examples": step * spec["batch_size"],
345
+ "counts": counts.copy(),
346
+ "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4,
347
+ "supervised_tokens": step * spec["batch_size"] * 2,
348
+ "estimated_training_flops": step * flop_step,
349
+ "last_batch_loss": last_loss,
350
+ }
351
+ predictions = {}
352
+ for name in names:
353
+ row[name], pred = evaluate_rows(model, world[name], device)
354
+ predictions.update({name + "_" + k: v for k, v in pred.items()})
355
+ row["two_calls"] = two_calls(model, world["test_composite"], device)
356
+ torch.cuda.synchronize()
357
+ elapsed_eval += time.perf_counter() - t0
358
+ row["evaluation_seconds"] = elapsed_eval
359
+ rows_log.append(row)
360
+ write_json(out / "learning.json", rows_log)
361
+ np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions)
362
+ state = {
363
+ "step": step,
364
+ "spec": spec,
365
+ "model": model.state_dict(),
366
+ "optimizer": opt.state_dict(),
367
+ "stream": stream.state_dict(),
368
+ "counts": counts,
369
+ "elapsed_training": elapsed_training,
370
+ "elapsed_eval": elapsed_eval,
371
+ "cpu_rng": torch.get_rng_state(),
372
+ "cuda_rng": torch.cuda.get_rng_state(device),
373
+ }
374
+ torch.save(state, out / "latest.tmp.pt")
375
+ (out / "latest.tmp.pt").replace(checkpoint)
376
+ if step in spec["weight_nodes"]:
377
+ torch.save(
378
+ {"spec": spec, "step": step, "model": model.state_dict()},
379
+ out / f"weights-{step:07d}.pt",
380
+ )
381
+ status = {
382
+ "state": "complete" if step == spec["steps"] else "running",
383
+ "step": step,
384
+ "budget": spec["steps"],
385
+ "updated_utc": utc(),
386
+ "atomic": row["atomic"]["accuracy"],
387
+ "train": row["train_composite"]["accuracy"],
388
+ "test": row["test_composite"]["accuracy"],
389
+ }
390
+ write_json(out / "status.json", status)
391
+ print(json.dumps(status), flush=True)
392
+ return row
393
+
394
+ if not resume:
395
+ measure(0)
396
+ nodes = [s for s in spec["nodes"] if s > start_step]
397
+ for end in nodes:
398
+ last_loss = None
399
+ torch.cuda.synchronize()
400
+ t0 = time.perf_counter()
401
+ step = start_step
402
+ while step < end:
403
+ n = min(512, end - step)
404
+ ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"])
405
+ atom_count = int((ix < len(world["atomic"])).sum())
406
+ counts["atomic"] += atom_count
407
+ counts["composite"] += ix.size - atom_count
408
+ gpu_ix = torch.as_tensor(ix, device=device)
409
+ for j in range(n):
410
+ lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"]))
411
+ last_loss = graph(gpu_ix[j])
412
+ step += n
413
+ torch.cuda.synchronize()
414
+ elapsed_training += time.perf_counter() - t0
415
+ loss_value = float(last_loss.detach())
416
+ if not math.isfinite(loss_value):
417
+ raise FloatingPointError(f"Nonfinite loss at step {end}")
418
+ row = measure(end, loss_value)
419
+ start_step = end
420
+ write_json(
421
+ out / "complete.json",
422
+ {
423
+ "finished_utc": utc(),
424
+ "spec": spec,
425
+ "parameters": nparams,
426
+ "training_seconds": elapsed_training,
427
+ "evaluation_seconds": elapsed_eval,
428
+ "endpoint": row,
429
+ },
430
+ )
431
+ return row
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prefix-only causal interventions on frozen grok-depth-v1 checkpoints.
2
+
3
+ Donors are selected from world facts before any model is loaded. The only donor
4
+ input is its two-token atomic query; second relations and answers never enter the
5
+ forward pass that supplies the post-first-block residual state.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import importlib
12
+ import json
13
+ import platform
14
+ import sys
15
+ import time
16
+ import types
17
+ from collections import Counter
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch.nn import functional as F
24
+
25
+ CONDITIONS = (
26
+ "baseline",
27
+ "identity_r1",
28
+ "different_bridge_r1",
29
+ "same_bridge_r1",
30
+ "different_bridge_h",
31
+ "different_bridge_h_r1",
32
+ "counterfactual_input",
33
+ )
34
+ DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction")
35
+
36
+
37
+ def utc():
38
+ return datetime.now(timezone.utc).isoformat()
39
+
40
+
41
+ def digest(path):
42
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
43
+
44
+
45
+ def read_json(path):
46
+ return json.loads(Path(path).read_text())
47
+
48
+
49
+ def write_json(path, value):
50
+ path = Path(path)
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ temporary = path.with_suffix(path.suffix + ".tmp")
53
+ temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
54
+ temporary.replace(path)
55
+
56
+
57
+ def require(condition, message):
58
+ if not condition:
59
+ raise AssertionError(message)
60
+
61
+
62
+ def _frozen_modules(source_dir, metadata):
63
+ """Verify all historical copies, then import exclusively from that snapshot."""
64
+ snapshot = source_dir / "source"
65
+ copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()}
66
+ verified = {}
67
+ for original, expected in metadata["files"].items():
68
+ matches = [
69
+ p for rel, p in copied.items() if original == rel or original.endswith("/" + rel)
70
+ ]
71
+ require(len(matches) == 1, f"missing or ambiguous historical copy: {original}")
72
+ path = matches[0]
73
+ actual = digest(path)
74
+ require(actual == expected, f"historical source hash mismatch: {path}")
75
+ verified[path.relative_to(snapshot).as_posix()] = actual
76
+ configs = [snapshot / p for p in verified if p.startswith("configs/")]
77
+ require(len(configs) == 1, "expected exactly one frozen configuration")
78
+ frozen = read_json(configs[0])
79
+ require(
80
+ {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"],
81
+ "historical metadata differs from its frozen configuration",
82
+ )
83
+ package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16]
84
+ namespace = types.ModuleType(package)
85
+ namespace.__path__ = [str(snapshot / "src/llm_memory_editability")]
86
+ sys.modules[package] = namespace
87
+ training = importlib.import_module(package + ".grok_depth")
88
+ data = importlib.import_module(package + ".grok_depth_data")
89
+ return training, data, verified
90
+
91
+
92
+ def load_source_run(source_dir, step, device="cuda:0"):
93
+ """Return a frozen model/world after source, world and checkpoint consistency checks."""
94
+ source_dir = Path(source_dir).resolve()
95
+ metadata = read_json(source_dir / "metadata.json")
96
+ spec = metadata["spec"]
97
+ require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch")
98
+ training, data, verified = _frozen_modules(source_dir, metadata)
99
+ require(step in spec["weight_nodes"], f"unregistered historical weight node {step}")
100
+ checkpoint_path = source_dir / f"weights-{step:07d}.pt"
101
+ checkpoint_hash = digest(checkpoint_path)
102
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
103
+ require(
104
+ checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch"
105
+ )
106
+ require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading")
107
+ if step == spec["steps"]:
108
+ latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False)
109
+ require(
110
+ latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch"
111
+ )
112
+ require(
113
+ checkpoint["model"].keys() == latest["model"].keys()
114
+ and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()),
115
+ "endpoint weights differ from latest checkpoint",
116
+ )
117
+ del latest
118
+ world_path = source_dir / "world.npz"
119
+ world_hash = digest(world_path)
120
+ with np.load(world_path, allow_pickle=False) as stored:
121
+ world = {key: stored[key].copy() for key in stored.files}
122
+ world["metadata"] = read_json(source_dir / "world-metadata.json")
123
+ require(digest(world_path) == world_hash, "world changed while loading")
124
+ audit = data.audit_world(world)
125
+ require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch")
126
+ require(
127
+ audit["dataset_sha256"] == world["metadata"]["dataset_sha256"],
128
+ "world content hash mismatch",
129
+ )
130
+ rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS})
131
+ require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch")
132
+ for key, array in world.items():
133
+ if key != "metadata":
134
+ require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}")
135
+ cfg = training.ModelConfig(
136
+ vocab_size=2 + spec["entities"] + spec["relations"],
137
+ width=spec["width"],
138
+ layers=spec["layers"],
139
+ heads=spec["heads"],
140
+ context=8,
141
+ )
142
+ model = training.SmallGPT(cfg, spec["dropout"]).to(device)
143
+ model.load_state_dict(checkpoint["model"], strict=True)
144
+ model.eval()
145
+ for parameter in model.parameters():
146
+ parameter.requires_grad_(False)
147
+ provenance = {
148
+ "source_dir": str(source_dir),
149
+ "source_hashes": verified,
150
+ "checkpoint_sha256": checkpoint_hash,
151
+ "world_file_sha256": world_hash,
152
+ "dataset_sha256": audit["dataset_sha256"],
153
+ "world_audit": audit,
154
+ "source_metadata_sha256": digest(source_dir / "metadata.json"),
155
+ "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"),
156
+ "world_regenerated_identically": True,
157
+ }
158
+ return model, world, spec, provenance
159
+
160
+
161
+ def _choose(candidates, world_hash, seed, row, kind):
162
+ """Content-based uniform deterministic selection; no model input is accepted."""
163
+ if not candidates:
164
+ return None
165
+ material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":"))
166
+ rng = np.random.default_rng(
167
+ int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big")
168
+ )
169
+ return sorted(candidates)[int(rng.integers(len(candidates)))]
170
+
171
+
172
+ def select_donors(world, seed):
173
+ """Select once per test row; preserve all rows, masks and rejection counts.
174
+
175
+ Different-bridge candidates share r1, change h/b/t, have ID second facts,
176
+ and yield a reserved-test or unused counterfactual. Same-bridge candidates
177
+ may change r1; only their bridge, query distinctness and h != original t
178
+ matter. No candidate is selected using model behavior.
179
+ """
180
+ rows = world["test_composite"]
181
+ n = len(rows)
182
+ atoms = {tuple(map(int, row)) for row in world["id_atomic"]}
183
+ lookup = {(h, r): t for h, r, t in atoms}
184
+ held_out = {
185
+ tuple(map(int, row))
186
+ for name in ("test_composite", "unused_composite")
187
+ for row in world[name]
188
+ }
189
+ training = {tuple(map(int, row)) for row in world["train_composite"]}
190
+ world_hash = world["metadata"]["dataset_sha256"]
191
+ out = {
192
+ "original_rows": rows.copy(),
193
+ "original_bridge": np.full(n, -1, dtype=np.int64),
194
+ "different_donor": np.full((n, 3), -1, dtype=np.int64),
195
+ "same_donor": np.full((n, 3), -1, dtype=np.int64),
196
+ "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64),
197
+ "different_valid": np.zeros(n, dtype=bool),
198
+ "same_valid": np.zeros(n, dtype=bool),
199
+ "different_reason": np.full(n, "", dtype="U64"),
200
+ "same_reason": np.full(n, "", dtype="U64"),
201
+ "different_candidate_count": np.zeros(n, dtype=np.int64),
202
+ "same_candidate_count": np.zeros(n, dtype=np.int64),
203
+ "same_relation_control": np.full(n, "missing", dtype="U24"),
204
+ "different_nondegenerate": np.zeros(n, dtype=bool),
205
+ }
206
+ rejection_names = (
207
+ "same_head",
208
+ "same_bridge",
209
+ "missing_id_second_fact",
210
+ "same_tail",
211
+ "head_is_answer",
212
+ "counterfactual_in_train",
213
+ "counterfactual_not_held_out",
214
+ )
215
+ for reason in rejection_names:
216
+ out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64)
217
+ for index, row in enumerate(rows):
218
+ h, r1, r2, tail = map(int, row)
219
+ bridge = lookup[h, r1]
220
+ require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain")
221
+ out["original_bridge"][index] = bridge
222
+ candidates = []
223
+ for dh, dr, db in sorted(atoms):
224
+ if dr != r1:
225
+ continue
226
+ dt = lookup.get((db, r2))
227
+ cf = (dh, r1, r2, dt)
228
+ reason = (
229
+ "same_head"
230
+ if dh == h
231
+ else "same_bridge"
232
+ if db == bridge
233
+ else "missing_id_second_fact"
234
+ if dt is None
235
+ else "same_tail"
236
+ if dt == tail
237
+ else "head_is_answer"
238
+ if dh in (tail, dt)
239
+ else "counterfactual_in_train"
240
+ if cf in training
241
+ else "counterfactual_not_held_out"
242
+ if cf not in held_out
243
+ else None
244
+ )
245
+ if reason:
246
+ out["different_rejected_" + reason][index] += 1
247
+ else:
248
+ candidates.append((dh, dr, db, dt))
249
+ donor = _choose(candidates, world_hash, seed, row, "different")
250
+ out["different_candidate_count"][index] = len(candidates)
251
+ if donor is None:
252
+ out["different_reason"][index] = "no_candidate_after_registered_exclusions"
253
+ else:
254
+ dh, dr, db, dt = donor
255
+ out["different_donor"][index] = dh, dr, db
256
+ out["counterfactual_rows"][index] = dh, r1, r2, dt
257
+ out["different_valid"][index] = True
258
+ out["different_reason"][index] = "eligible"
259
+ out["different_nondegenerate"][index] = db != dt and db != tail
260
+ candidates = [
261
+ (dh, dr, db)
262
+ for dh, dr, db in atoms
263
+ if db == bridge and (dh, dr) != (h, r1) and dh != tail
264
+ ]
265
+ same_relation = [candidate for candidate in candidates if candidate[1] == r1]
266
+ donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same")
267
+ out["same_candidate_count"][index] = len(candidates)
268
+ if donor is None:
269
+ out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer"
270
+ else:
271
+ out["same_donor"][index] = donor
272
+ out["same_valid"][index] = True
273
+ out["same_reason"][index] = "eligible"
274
+ out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1"
275
+ return out
276
+
277
+
278
+ @torch.no_grad()
279
+ def traced_forward(
280
+ model,
281
+ tokens,
282
+ positions=None,
283
+ donor_state=None,
284
+ patch_positions=(),
285
+ identity=False,
286
+ return_state=False,
287
+ ):
288
+ """Frozen SmallGPT eval forward, replacing residuals after complete block 0.
289
+
290
+ Both attention and MLP in the first block run before replacement. There is
291
+ no patch in another block, and final LN/output projection remain untouched.
292
+ """
293
+ require(not model.training, "interventions require model.eval()")
294
+ require(
295
+ donor_state is None or not identity, "identity and donor patches are mutually exclusive"
296
+ )
297
+ x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device))
298
+ first_state = None
299
+ for index, block in enumerate(model.blocks):
300
+ z = block.ln1(x)
301
+ batch, length, width = z.shape
302
+ attention = block.attention
303
+ q, k, v = (
304
+ attention.qkv(z)
305
+ .view(batch, length, 3, attention.heads, width // attention.heads)
306
+ .unbind(2)
307
+ )
308
+ y = F.scaled_dot_product_attention(
309
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0
310
+ )
311
+ y = attention.proj(y.transpose(1, 2).reshape(batch, length, width))
312
+ x = x + y
313
+ x = x + block.mlp(block.ln2(x))
314
+ if index == 0:
315
+ if return_state:
316
+ first_state = x.clone()
317
+ if donor_state is not None or identity:
318
+ x = x.clone()
319
+ replacement = x.clone() if identity else donor_state
320
+ for position in patch_positions:
321
+ x[:, position, :] = replacement[:, position, :]
322
+ x = model.ln_final(x)
323
+ if positions is not None:
324
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
325
+ logits = F.linear(x, model.token.weight)
326
+ return (logits, first_state) if return_state else logits
327
+
328
+
329
+ @torch.no_grad()
330
+ def prefix_state(model, prefixes):
331
+ """Two informative tokens, padded to the historical four-position shape.
332
+
333
+ Both suffix tokens are the fixed PAD token, never a relation or answer.
334
+ Causality makes the retained two states independent of these suffixes.
335
+ Matching the matrix shapes avoids TF32 kernel-dependent rounding changes.
336
+ """
337
+ require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes")
338
+ padded = F.pad(prefixes, (0, 2), value=0)
339
+ _, state = traced_forward(model, padded, return_state=True)
340
+ return state[:, :2]
341
+
342
+
343
+ @torch.no_grad()
344
+ def evaluate_condition(
345
+ model,
346
+ rows,
347
+ device,
348
+ batch_size=1024,
349
+ donor_prefixes=None,
350
+ patch_positions=(),
351
+ identity=False,
352
+ verify_trace=False,
353
+ ):
354
+ """Answer generation followed by EOS with the generated answer fed back.
355
+
356
+ The exact same prefix state is reapplied on the second forward pass. Arrays
357
+ are local to the supplied rows; the caller scatters them to the full test set.
358
+ """
359
+ n = len(rows)
360
+ answers, stops, original_logits = [], [], []
361
+ trace_max_delta, trace_disagreements = 0.0, 0
362
+ prefix_max_delta = 0.0
363
+ for start in range(0, n, batch_size):
364
+ selected = rows[start : start + batch_size]
365
+ arity = rows.shape[1]
366
+ require(arity in (3, 4), "expected atomic or composite rows")
367
+ packed = np.zeros((len(selected), 4), dtype=np.int64)
368
+ packed[:, :arity] = selected
369
+ x = torch.as_tensor(packed, device=device)
370
+ pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device)
371
+ donor_state = None
372
+ if donor_prefixes is not None:
373
+ prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device)
374
+ require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1")
375
+ donor_state = prefix_state(model, prefixes)
376
+ logits = traced_forward(model, x, pos, donor_state, patch_positions, identity)
377
+ if verify_trace:
378
+ reference = model(x, pos)
379
+ trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max()))
380
+ trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum())
381
+ prefix = prefix_state(model, x[:, :2])
382
+ _, whole = traced_forward(model, x, return_state=True)
383
+ prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max()))
384
+ require(
385
+ torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4),
386
+ "pure-prefix state does not match causal full-input prefix",
387
+ )
388
+ answer = logits[:, 0].argmax(-1)
389
+ original_logits.append(logits[:, 0].cpu().numpy())
390
+ x[:, arity - 1] = answer
391
+ generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity)
392
+ if verify_trace:
393
+ reference = model(x, pos)
394
+ trace_max_delta = max(
395
+ trace_max_delta, float((reference - generated_logits).abs().max())
396
+ )
397
+ trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum())
398
+ answers.append(answer.cpu().numpy())
399
+ stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy())
400
+ require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs")
401
+ require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}")
402
+ return {
403
+ "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64),
404
+ "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64),
405
+ "answer_logits": np.concatenate(original_logits)
406
+ if n
407
+ else np.empty((0, model.token.num_embeddings), dtype=np.float32),
408
+ }, {
409
+ "standard_forward_max_logit_delta": trace_max_delta,
410
+ "standard_forward_argmax_disagreements": trace_disagreements,
411
+ "prefix_vs_full_first_block_max_delta": prefix_max_delta,
412
+ "trace_comparison_performed": verify_trace,
413
+ }
414
+
415
+
416
+ def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer):
417
+ count = int(selected.sum())
418
+ counterfactual = selected & cf_valid
419
+ ncf = int(counterfactual.sum())
420
+ correct = answer == original
421
+ cf_correct = answer == cf
422
+ return {
423
+ "n": count,
424
+ "total_test_n": total,
425
+ "coverage": count / total if total else None,
426
+ "original_answer_accuracy": float(correct[selected].mean()) if count else None,
427
+ "original_complete_accuracy": float((correct & (stop == 1))[selected].mean())
428
+ if count
429
+ else None,
430
+ "eos_accuracy": float((stop[selected] == 1).mean()) if count else None,
431
+ "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean())
432
+ if count
433
+ else None,
434
+ "cf_target_n": ncf,
435
+ "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None,
436
+ "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean())
437
+ if ncf
438
+ else None,
439
+ }
440
+
441
+
442
+ def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024):
443
+ """Evaluate all fixed conditions, then expose full and prerequisite subgroups."""
444
+ started = time.perf_counter()
445
+ rows = world["test_composite"]
446
+ n = len(rows)
447
+ different, same = donors["different_valid"], donors["same_valid"]
448
+ arrays = {key: value.copy() for key, value in donors.items()}
449
+ audits = {}
450
+ for condition in CONDITIONS:
451
+ mask = (
452
+ same
453
+ if condition == "same_bridge_r1"
454
+ else different
455
+ if condition.startswith("different_") or condition == "counterfactual_input"
456
+ else np.ones(n, dtype=bool)
457
+ )
458
+ eval_rows = (
459
+ donors["counterfactual_rows"][mask]
460
+ if condition == "counterfactual_input"
461
+ else rows[mask]
462
+ )
463
+ donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor"
464
+ donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None
465
+ positions = (
466
+ (0, 1)
467
+ if condition == "different_bridge_h_r1"
468
+ else (0,)
469
+ if condition == "different_bridge_h"
470
+ else (1,)
471
+ )
472
+ result, audit = evaluate_condition(
473
+ model,
474
+ eval_rows,
475
+ device,
476
+ batch_size,
477
+ donor_prefix,
478
+ positions,
479
+ condition == "identity_r1",
480
+ condition == "baseline",
481
+ )
482
+ audits[condition] = audit
483
+ answer = np.full(n, -1, dtype=np.int64)
484
+ stop = np.full(n, -1, dtype=np.int64)
485
+ answer[mask], stop[mask] = result["answer"], result["stop"]
486
+ arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop
487
+ arrays[condition + "_valid"] = mask
488
+ original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]]
489
+ cf_logit = np.full(n, np.nan, dtype=np.float32)
490
+ cf_local = different[mask]
491
+ cf_logit[mask.nonzero()[0][cf_local]] = (
492
+ result["answer_logits"][
493
+ np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1]
494
+ ]
495
+ - original_logit[cf_local]
496
+ )
497
+ arrays[condition + "_cf_minus_original_logit"] = cf_logit
498
+ for column in ("answer", "stop"):
499
+ require(
500
+ np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]),
501
+ f"identity patch changed {column}",
502
+ )
503
+ if len(model.blocks) == 1:
504
+ for condition in (
505
+ "different_bridge_r1",
506
+ "same_bridge_r1",
507
+ "different_bridge_h",
508
+ "different_bridge_h_r1",
509
+ ):
510
+ valid = arrays[condition + "_valid"]
511
+ require(
512
+ np.array_equal(
513
+ arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid]
514
+ ),
515
+ f"one-layer structural negative control changed {condition}.{column}",
516
+ )
517
+ baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1)
518
+ cf_correct = (
519
+ different
520
+ & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1])
521
+ & (arrays["counterfactual_input_stop"] == 1)
522
+ )
523
+ atomic_rows = {
524
+ "different_first": (donors["different_donor"], different),
525
+ "counterfactual_second": (
526
+ np.c_[
527
+ donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1]
528
+ ],
529
+ different,
530
+ ),
531
+ "same_first": (donors["same_donor"], same),
532
+ }
533
+ atomic_scores = {}
534
+ atomic_correct = {}
535
+ for name, (facts, mask) in atomic_rows.items():
536
+ prediction, _ = evaluate_condition(model, facts[mask], device, batch_size)
537
+ answer = np.full(n, -1, dtype=np.int64)
538
+ stop = np.full(n, -1, dtype=np.int64)
539
+ answer[mask], stop[mask] = prediction["answer"], prediction["stop"]
540
+ arrays["atomic_" + name + "_rows"] = facts.copy()
541
+ arrays["atomic_" + name + "_answer"] = answer
542
+ arrays["atomic_" + name + "_stop"] = stop
543
+ arrays["atomic_" + name + "_valid"] = mask.copy()
544
+ correct = mask & (answer == facts[:, -1])
545
+ atomic_correct[name] = correct & (stop == 1)
546
+ count = int(mask.sum())
547
+ atomic_scores[name] = {
548
+ "n": count,
549
+ "total_test_n": n,
550
+ "coverage": count / n if n else None,
551
+ "answer_accuracy": float(correct[mask].mean()) if count else None,
552
+ "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None,
553
+ "eos_accuracy": float((stop[mask] == 1).mean()) if count else None,
554
+ }
555
+ groups = {
556
+ "all_test": np.ones(n, dtype=bool),
557
+ "different_donor_available": different,
558
+ "same_donor_available": same,
559
+ "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct,
560
+ "different_bridge_nondegenerate": donors["different_nondegenerate"],
561
+ "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"),
562
+ "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"),
563
+ "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"]
564
+ & atomic_correct["counterfactual_second"],
565
+ }
566
+ for group, mask in groups.items():
567
+ arrays["subset_" + group] = mask
568
+ scores = {
569
+ group: {
570
+ "subset_n": int(mask.sum()),
571
+ "total_test_n": n,
572
+ "coverage": float(mask.mean()) if n else None,
573
+ "conditions": {
574
+ condition: _metrics(
575
+ arrays[condition + "_answer"],
576
+ arrays[condition + "_stop"],
577
+ rows[:, -1],
578
+ donors["counterfactual_rows"][:, -1],
579
+ mask & arrays[condition + "_valid"],
580
+ different,
581
+ n,
582
+ arrays["baseline_answer"],
583
+ )
584
+ for condition in CONDITIONS
585
+ },
586
+ }
587
+ for group, mask in groups.items()
588
+ }
589
+ summary = {
590
+ "conditions": list(CONDITIONS),
591
+ "scores": scores,
592
+ "atomic_preconditions": atomic_scores,
593
+ "donor_coverage": {
594
+ "total_test_n": n,
595
+ "different_n": int(different.sum()),
596
+ "same_n": int(same.sum()),
597
+ "different_reasons": dict(Counter(donors["different_reason"].tolist())),
598
+ "same_reasons": dict(Counter(donors["same_reason"].tolist())),
599
+ "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())),
600
+ },
601
+ "engineering_checks": {
602
+ "identity_predictions_equal": True,
603
+ "one_layer_all_early_position_patch_predictions_equal": True
604
+ if len(model.blocks) == 1
605
+ else None,
606
+ "trace": audits["baseline"],
607
+ "eos_uses_generated_answer_and_reapplies_patch": True,
608
+ "donor_nonpadding_input_tokens": 2,
609
+ "donor_forward_sequence_length": 4,
610
+ "donor_pad_token": 0,
611
+ },
612
+ "evaluation_seconds": time.perf_counter() - started,
613
+ }
614
+ return summary, arrays
615
+
616
+
617
+ def environment(device):
618
+ return {
619
+ "python": platform.python_version(),
620
+ "platform": platform.platform(),
621
+ "torch": torch.__version__,
622
+ "numpy": np.__version__,
623
+ "cuda": torch.version.cuda,
624
+ "device": str(device),
625
+ "gpu": torch.cuda.get_device_name(torch.device(device))
626
+ if str(device).startswith("cuda")
627
+ else None,
628
+ "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32,
629
+ "cudnn_tf32": torch.backends.cudnn.allow_tf32,
630
+ "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly",
631
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_data.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb.
2
+
3
+ Source: https://github.com/OSU-NLP-Group/GrokkedTransformer
4
+ Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT).
5
+
6
+ The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling
7
+ follow the authors' construction. Differences: integer tokens replace text;
8
+ randomness is local and seeded; atomic ordering is stable; graph size and the
9
+ reserved ID-test fraction are configurable. Unselected ID chains are returned
10
+ for audit only. No graph is regenerated to improve OOD counts or model results.
11
+
12
+ Adapted source license:
13
+ MIT License
14
+ Copyright (c) 2024 OSU Natural Language Processing
15
+
16
+ Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ of this software and associated documentation files (the "Software"), to deal
18
+ in the Software without restriction, including without limitation the rights
19
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ copies of the Software, and to permit persons to whom the Software is
21
+ furnished to do so, subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be included in all
24
+ copies or substantial portions of the Software.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
+ SOFTWARE.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import hashlib
38
+ import math
39
+
40
+ import numpy as np
41
+
42
+ PAD_TOKEN = 0
43
+ EOS_TOKEN = 1
44
+ ENTITY_OFFSET = 2
45
+ SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer"
46
+ SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c"
47
+ ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic")
48
+ COMPOSITE_SPLITS = (
49
+ "train_composite",
50
+ "test_composite",
51
+ "ood_composite",
52
+ "unused_composite",
53
+ )
54
+
55
+
56
+ def _array(rows: list, columns: int) -> np.ndarray:
57
+ return np.asarray(rows, dtype=np.int64).reshape(-1, columns)
58
+
59
+
60
+ def build_world(
61
+ seed: int,
62
+ entities: int = 128,
63
+ relations: int = 16,
64
+ degree: int = 8,
65
+ phi: float = 8.0,
66
+ id_fraction: float = 0.95,
67
+ id_test_fraction: float = 0.005,
68
+ ) -> dict:
69
+ """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays.
70
+
71
+ All atomics belong in training, including those labelled OOD. OOD refers
72
+ to *composition experience*: neither constituent of an OOD composite is
73
+ allowed in composite training. Mixed ID/OOD chains are excluded. The
74
+ test set is reserved before phi downsampling; unused ID chains are never
75
+ automatically reassigned to test. ``phi`` is relative to ID atomics, as in
76
+ the source. Requests larger than the available training pool are capped
77
+ and explicitly recorded. Empty test sets are retained and reported.
78
+
79
+ Query tokens are every column except the last; the last is the entity
80
+ answer. EOS supervision, padding, and loss masks belong to the trainer.
81
+ """
82
+ for name, value in (("entities", entities), ("relations", relations), ("degree", degree)):
83
+ if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1:
84
+ raise ValueError(f"{name} must be a positive integer")
85
+ if degree > relations:
86
+ raise ValueError("degree cannot exceed relations")
87
+ if not math.isfinite(phi) or phi < 0:
88
+ raise ValueError("phi must be finite and nonnegative")
89
+ if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1:
90
+ raise ValueError("id_fraction must be in [0, 1]")
91
+ if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1:
92
+ raise ValueError("id_test_fraction must be in [0, 1]")
93
+
94
+ # RandomState keeps the source's NumPy draw family, without global RNG use.
95
+ rng = np.random.RandomState(seed)
96
+ relation_offset = ENTITY_OFFSET + entities
97
+ rows = []
98
+ outgoing = [[] for _ in range(entities)]
99
+ for head_index in range(entities):
100
+ selected = rng.choice(relations, size=degree, replace=False)
101
+ for relation_index in selected:
102
+ tail_index = int(rng.randint(entities))
103
+ edge = (
104
+ head_index + ENTITY_OFFSET,
105
+ int(relation_index) + relation_offset,
106
+ tail_index + ENTITY_OFFSET,
107
+ )
108
+ outgoing[head_index].append(len(rows))
109
+ rows.append(edge)
110
+ atomic = _array(rows, 3)
111
+ ood_count = round(len(atomic) * (1 - id_fraction))
112
+ ood_mask = np.zeros(len(atomic), dtype=bool)
113
+ ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True
114
+
115
+ eligible, test, ood = [], [], []
116
+ mixed_count = 0
117
+ for first_index, (head, relation1, bridge) in enumerate(atomic):
118
+ for second_index in outgoing[int(bridge) - ENTITY_OFFSET]:
119
+ _, relation2, tail = atomic[second_index]
120
+ row = (head, relation1, relation2, tail)
121
+ first_ood, second_ood = ood_mask[first_index], ood_mask[second_index]
122
+ if first_ood and second_ood:
123
+ ood.append(row)
124
+ elif first_ood or second_ood:
125
+ mixed_count += 1
126
+ elif rng.uniform() > id_test_fraction:
127
+ eligible.append(row)
128
+ else:
129
+ test.append(row)
130
+
131
+ requested_count = round(phi * int((~ood_mask).sum()))
132
+ train_count = min(requested_count, len(eligible))
133
+ # Source choose() returns the full pool unchanged when it is saturated.
134
+ indices = (
135
+ np.arange(len(eligible))
136
+ if train_count == len(eligible)
137
+ else rng.choice(len(eligible), size=train_count, replace=False)
138
+ )
139
+ eligible_array = _array(eligible, 4)
140
+ selected_mask = np.zeros(len(eligible), dtype=bool)
141
+ selected_mask[indices] = True
142
+ world = {
143
+ "atomic": atomic,
144
+ "id_atomic": atomic[~ood_mask],
145
+ "ood_atomic": atomic[ood_mask],
146
+ "train_composite": eligible_array[indices],
147
+ "test_composite": _array(test, 4),
148
+ "ood_composite": _array(ood, 4),
149
+ "unused_composite": eligible_array[~selected_mask],
150
+ "metadata": {
151
+ "seed": int(seed),
152
+ "entities": int(entities),
153
+ "relations": int(relations),
154
+ "degree": int(degree),
155
+ "phi_requested": float(phi),
156
+ "id_fraction": float(id_fraction),
157
+ "id_test_fraction": float(id_test_fraction),
158
+ "pad_token": PAD_TOKEN,
159
+ "eos_token": EOS_TOKEN,
160
+ "entity_offset": ENTITY_OFFSET,
161
+ "relation_offset": int(relation_offset),
162
+ "vocab_size": int(relation_offset + relations),
163
+ "train_composite_requested": int(requested_count),
164
+ "train_composite_capped": requested_count > len(eligible),
165
+ "phi_actual": train_count / max(int((~ood_mask).sum()), 1),
166
+ "mixed_composite_excluded": mixed_count,
167
+ "source_url": SOURCE_URL,
168
+ "source_commit": SOURCE_COMMIT,
169
+ "source_file": "composition.ipynb",
170
+ "source_license": "MIT",
171
+ "construction_differences": [
172
+ "integer tokens and local seeded RNG",
173
+ "stable atomic ordering instead of Python set iteration",
174
+ "configurable graph size and ID-test reserve fraction",
175
+ "all evaluation rows retained instead of sampling at most 3000",
176
+ ],
177
+ },
178
+ }
179
+ audit = audit_world(world)
180
+ world["metadata"]["counts"] = audit["counts"]
181
+ world["metadata"]["dataset_sha256"] = audit["dataset_sha256"]
182
+ world["metadata"]["warnings"] = audit["warnings"]
183
+ return world
184
+
185
+
186
+ def audit_world(world: dict) -> dict:
187
+ """Validate token ranges, graph truth, exhaustive partitions and no leakage.
188
+
189
+ Raises ValueError on a broken contract; zero-sized test sets and capped
190
+ training pools are valid and surfaced as warnings, never resampled.
191
+ """
192
+ metadata = world["metadata"]
193
+ entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree"))
194
+ relation_offset = entities + ENTITY_OFFSET
195
+ digest = hashlib.sha256()
196
+ counts = {}
197
+ tuples = {}
198
+ for name in ATOMIC_SPLITS + COMPOSITE_SPLITS:
199
+ array = world[name]
200
+ columns = 3 if name in ATOMIC_SPLITS else 4
201
+ if not isinstance(array, np.ndarray) or array.dtype != np.int64:
202
+ raise ValueError(f"{name} must be an int64 numpy array")
203
+ if array.ndim != 2 or array.shape[1] != columns:
204
+ raise ValueError(f"{name} must have {columns} columns")
205
+ for column in (0, columns - 1):
206
+ if np.any(array[:, column] < ENTITY_OFFSET) or np.any(
207
+ array[:, column] >= relation_offset
208
+ ):
209
+ raise ValueError(f"{name} has an invalid entity token")
210
+ if np.any(array[:, 1:-1] < relation_offset) or np.any(
211
+ array[:, 1:-1] >= relation_offset + relations
212
+ ):
213
+ raise ValueError(f"{name} has an invalid relation token")
214
+ rows = {tuple(map(int, row)) for row in array}
215
+ if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows):
216
+ raise ValueError(f"{name} has duplicate or conflicting queries")
217
+ tuples[name] = rows
218
+ counts[name] = len(array)
219
+ digest.update(name.encode())
220
+ digest.update(np.asarray(array.shape, dtype="<i8").tobytes())
221
+ digest.update(array.astype("<i8", copy=False).tobytes())
222
+
223
+ atomics, id_atomics, ood_atomics = (tuples[name] for name in ATOMIC_SPLITS)
224
+ if id_atomics & ood_atomics or id_atomics | ood_atomics != atomics:
225
+ raise ValueError("ID/OOD atomics do not partition all atomic facts")
226
+ if len(atomics) != entities * degree:
227
+ raise ValueError("incorrect atomic graph size")
228
+ outgoing = {}
229
+ lookup = {}
230
+ for head, relation, tail in atomics:
231
+ outgoing.setdefault(head, []).append((relation, tail))
232
+ lookup[head, relation] = tail
233
+ if len(outgoing) != entities or any(len(edges) != degree for edges in outgoing.values()):
234
+ raise ValueError("incorrect per-entity out-degree")
235
+
236
+ id_chains, ood_chains, mixed_count = set(), set(), 0
237
+ for head, relation1, bridge in atomics:
238
+ for relation2, tail in outgoing[bridge]:
239
+ row = (head, relation1, relation2, tail)
240
+ first_id = (head, relation1, bridge) in id_atomics
241
+ second_id = (bridge, relation2, tail) in id_atomics
242
+ if first_id and second_id:
243
+ id_chains.add(row)
244
+ elif not first_id and not second_id:
245
+ ood_chains.add(row)
246
+ else:
247
+ mixed_count += 1
248
+ occupied = set()
249
+ for name in COMPOSITE_SPLITS:
250
+ rows = tuples[name]
251
+ if rows & occupied:
252
+ raise ValueError("composite splits overlap")
253
+ occupied |= rows
254
+ for head, relation1, relation2, tail in rows:
255
+ bridge = lookup.get((head, relation1))
256
+ if bridge is None or lookup.get((bridge, relation2)) != tail:
257
+ raise ValueError(f"{name} contains a false chain")
258
+ expected = ood_chains if name == "ood_composite" else id_chains
259
+ if not rows <= expected:
260
+ raise ValueError(f"{name} contains chains from the wrong atomic split")
261
+ returned_id = set().union(
262
+ *(tuples[name] for name in COMPOSITE_SPLITS if name != "ood_composite")
263
+ )
264
+ if returned_id != id_chains or tuples["ood_composite"] != ood_chains:
265
+ raise ValueError("composite partitions omit eligible graph chains")
266
+ if mixed_count != metadata["mixed_composite_excluded"]:
267
+ raise ValueError("incorrect excluded mixed-chain count")
268
+ warnings = [
269
+ f"{name} is empty" for name in ("test_composite", "ood_composite") if not counts[name]
270
+ ]
271
+ if metadata["train_composite_capped"]:
272
+ warnings.append("requested phi exceeds available composite training pool")
273
+ return {
274
+ "ok": True,
275
+ "counts": counts,
276
+ "id_composite_total": len(id_chains),
277
+ "ood_composite_total": len(ood_chains),
278
+ "mixed_composite_excluded": mixed_count,
279
+ "dataset_sha256": digest.hexdigest(),
280
+ "warnings": warnings,
281
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_extension.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen paired depth extension: validation and threshold accounting only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+
9
+
10
+ def digest(path):
11
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
12
+
13
+
14
+ def read_json(path):
15
+ return json.loads(Path(path).read_text())
16
+
17
+
18
+ def validate_pair(spec, baseline):
19
+ """Only the layer count and bookkeeping phase may differ from the old baseline."""
20
+ assert baseline["layers"] == 2
21
+ assert spec["layers"] in (3, 4)
22
+ ignored = {"layers", "phase"}
23
+ assert {k: v for k, v in spec.items() if k not in ignored} == {
24
+ k: v for k, v in baseline.items() if k not in ignored
25
+ }, "Extension changes a non-depth training condition"
26
+
27
+
28
+ def threshold_time(rows, threshold, counts, budget):
29
+ """First start of three registered consecutive nodes; never choose a best node."""
30
+ assert 0 <= threshold <= 1
31
+ steps = [row["step"] for row in rows]
32
+ assert steps == sorted(set(steps)), "Unsorted or duplicate evaluation nodes"
33
+ assert not steps or steps[-1] <= budget
34
+ result = {
35
+ "threshold": threshold,
36
+ "reached": False,
37
+ "step": None,
38
+ "confirmed_at_step": None,
39
+ "previous_evaluation_step": None,
40
+ "examples": None,
41
+ "atomic_exposures": None,
42
+ "composite_exposures": None,
43
+ "dataset_passes": None,
44
+ "estimated_training_flops": None,
45
+ "effective_input_tokens": None,
46
+ "supervised_tokens": None,
47
+ "last_observed_step": steps[-1] if steps else None,
48
+ "budget_steps": budget,
49
+ }
50
+ for i in range(max(0, len(rows) - 2)):
51
+ triple = rows[i : i + 3]
52
+ if all(row["test_composite"]["accuracy"] >= threshold for row in triple):
53
+ row = triple[0]
54
+ result.update(
55
+ reached=True,
56
+ step=row["step"],
57
+ confirmed_at_step=triple[-1]["step"],
58
+ previous_evaluation_step=rows[i - 1]["step"] if i else None,
59
+ examples=row["examples"],
60
+ atomic_exposures=row["counts"]["atomic"] / counts["atomic"],
61
+ composite_exposures=row["counts"]["composite"] / counts["train_composite"],
62
+ dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]),
63
+ estimated_training_flops=row["estimated_training_flops"],
64
+ effective_input_tokens=row["effective_input_tokens"],
65
+ supervised_tokens=row["supervised_tokens"],
66
+ )
67
+ break
68
+ return result
69
+
70
+
71
+ def verify_files(root, expected):
72
+ for relative, sha in expected.items():
73
+ assert digest(root / relative) == sha, f"Frozen input changed: {relative}"
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_data.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audited data and fixed atomic/composite exposure for loop-depth comparisons.
2
+
3
+ The graph, truth, complete-query holdout and phi sampling are inherited from
4
+ ``grok_multihop_data``. Changing the atomic ID fraction is an explicit design
5
+ choice; no graph is regenerated in response to diagnostics or model scores.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ from collections.abc import Mapping
12
+
13
+ import numpy as np
14
+
15
+ from . import grok_multihop_data as multihop
16
+
17
+ SPLITS = multihop.SPLITS
18
+ DATA_DEFAULTS = {
19
+ "hops": 2,
20
+ "entities": 128,
21
+ "relations": 16,
22
+ "degree": 8,
23
+ "phi": 6.0,
24
+ "id_fraction": 0.95,
25
+ "id_test_fraction": 0.1,
26
+ "evaluation_size": 1024,
27
+ }
28
+
29
+
30
+ def build_world(spec: Mapping) -> dict:
31
+ """Adapt a flat run specification while retaining the historical world API.
32
+
33
+ ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are
34
+ ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit
35
+ ``id_fraction=0.75`` for the new composition-experience comparison.
36
+
37
+ ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j
38
+ fact in ``world['atomic']``. These truth indices are evaluation artifacts;
39
+ training must only use the original atomic and train-composite rows.
40
+ """
41
+ if "world_seed" not in spec and "seed" not in spec:
42
+ raise ValueError("spec must contain world_seed or seed")
43
+ seed = spec.get("world_seed", spec.get("seed"))
44
+ fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()}
45
+ world = multihop.build_world(seed, **fields)
46
+ world["relevant_atomic_indices"] = {
47
+ name: query_atomic_indices(world, world[name]) for name in SPLITS
48
+ }
49
+ world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world)
50
+ world["metadata"]["loop_data_contract"] = {
51
+ "constructor": "grok_multihop_data.build_world",
52
+ "world_selection": "fixed supplied seed; no diagnostic or model-based selection",
53
+ "all_atomic_rows_are_training_facts": True,
54
+ "ood_definition": "all constituent facts absent from composite training by split",
55
+ "query_fact_indices": "evaluation truth only; no intermediate-entity supervision",
56
+ "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors",
57
+ }
58
+ audit_world(world)
59
+ return world
60
+
61
+
62
+ def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray:
63
+ """Return true constituent fact indices, including [N, 1] for atomics."""
64
+ meta = world["metadata"]
65
+ _, edges = multihop.path_details(
66
+ rows, world["atomic"], int(meta["entities"]), int(meta["relations"])
67
+ )
68
+ return edges
69
+
70
+
71
+ def audit_world(world: dict) -> dict:
72
+ """Independently verify truth, ID/OOD partitions and recorded fact indices.
73
+
74
+ The reused auditor checks truth by graph traversal and counts all-ID and
75
+ all-OOD paths by dynamic programming, independently of path construction.
76
+ Neither correct-looking diagnostics nor a saved metadata hash substitutes
77
+ for those checks.
78
+ """
79
+ result = multihop.audit_world(world)
80
+ recorded = world.get("relevant_atomic_indices")
81
+ if recorded is not None:
82
+ if set(recorded) != set(SPLITS):
83
+ raise ValueError("Relevant atomic indices must cover every data split")
84
+ for name in SPLITS:
85
+ expected = query_atomic_indices(world, world[name])
86
+ if (
87
+ not isinstance(recorded[name], np.ndarray)
88
+ or recorded[name].dtype != np.int64
89
+ or not np.array_equal(recorded[name], expected)
90
+ ):
91
+ raise ValueError(f"Incorrect relevant atomic indices: {name}")
92
+ if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"):
93
+ raise ValueError("Recorded dataset hash disagrees with actual data")
94
+ return {**result, "relevant_atomic_indices_checked": recorded is not None}
95
+
96
+
97
+ def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]:
98
+ """Describe target concentration after omitting the head and prefix relations.
99
+
100
+ The empirical modal fraction sums each suffix group's largest target count
101
+ and divides by query count. It uses the same rows to count and summarize;
102
+ singleton suffixes score one automatically. It is not a model-independent
103
+ generalization bound, a learned baseline, or proof that heads are unnecessary.
104
+ """
105
+ results = []
106
+ n = len(rows)
107
+ for length in range(1, rows.shape[1] - 1):
108
+ suffix = rows[:, -(length + 1) : -1]
109
+ if not n:
110
+ results.append(
111
+ {
112
+ "suffix_relation_count": length,
113
+ "groups": 0,
114
+ "empirical_modal_target_fraction": None,
115
+ "single_target_group_query_fraction": None,
116
+ "singleton_group_query_fraction": None,
117
+ "multi_query_groups": 0,
118
+ "multi_query_coverage_fraction": None,
119
+ "multi_query_empirical_modal_target_fraction": None,
120
+ "multi_target_groups": 0,
121
+ "same_suffix_different_target_example": None,
122
+ }
123
+ )
124
+ continue
125
+ _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True)
126
+ pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True)
127
+ maxima = np.zeros(len(totals), dtype=np.int64)
128
+ np.maximum.at(maxima, pairs[:, 0], pair_counts)
129
+ multi = totals > 1
130
+ multi_n = int(totals[multi].sum())
131
+ multi_target = maxima != totals
132
+ example = None
133
+ if multi_target.any():
134
+ # Deterministic first lexicographic suffix with incompatible targets.
135
+ group = int(np.flatnonzero(multi_target)[0])
136
+ members = np.flatnonzero(groups == group)
137
+ first = members[0]
138
+ second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]]
139
+ example = [rows[first].tolist(), rows[second].tolist()]
140
+ results.append(
141
+ {
142
+ "suffix_relation_count": length,
143
+ "groups": len(totals),
144
+ "empirical_modal_target_fraction": float(maxima.sum() / n),
145
+ "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n),
146
+ "singleton_group_query_fraction": float((totals == 1).sum() / n),
147
+ "multi_query_groups": int(multi.sum()),
148
+ "multi_query_coverage_fraction": float(multi_n / n),
149
+ "multi_query_empirical_modal_target_fraction": (
150
+ float(maxima[multi].sum() / multi_n) if multi_n else None
151
+ ),
152
+ "multi_target_groups": int(multi_target.sum()),
153
+ "same_suffix_different_target_example": example,
154
+ }
155
+ )
156
+ return results
157
+
158
+
159
+ def majority_tail_diagnostics(rows: np.ndarray) -> dict:
160
+ """Report the empirical within-split majority target, without fitting a model."""
161
+ if not len(rows):
162
+ return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0}
163
+ targets, counts = np.unique(rows[:, -1], return_counts=True)
164
+ index = int(counts.argmax())
165
+ return {
166
+ "target_token": int(targets[index]),
167
+ "count": int(counts[index]),
168
+ "fraction": float(counts[index] / len(rows)),
169
+ "distinct_targets": len(targets),
170
+ }
171
+
172
+
173
+ def data_diagnostics(world: dict) -> dict:
174
+ """Pure data coverage and target distributions; never evaluate a predictor."""
175
+ atomic_n = len(world["atomic"])
176
+ indices = world.get("relevant_atomic_indices")
177
+ if indices is None:
178
+ indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS}
179
+ training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n)
180
+ id_facts = np.zeros(atomic_n, dtype=bool)
181
+ id_facts[indices["id_atomic"].ravel()] = True
182
+ training_majority = majority_tail_diagnostics(world["train_composite"])
183
+ per_split = {}
184
+ for name in SPLITS:
185
+ rows, edges = world[name], indices[name]
186
+ distinct = np.unique(edges)
187
+ trained = training_counts[edges] > 0
188
+ all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1)
189
+ per_split[name] = {
190
+ "n": len(rows),
191
+ "unique_relevant_atomic_facts": len(distinct),
192
+ "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n,
193
+ "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None,
194
+ "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()),
195
+ "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()),
196
+ "relevant_fact_occurrences_seen_in_composite_training_fraction": (
197
+ float(trained.mean()) if edges.size else None
198
+ ),
199
+ "all_id_queries": int(all_id.sum()),
200
+ "all_ood_queries": int(all_ood.sum()),
201
+ "mixed_queries": int((~all_id & ~all_ood).sum()),
202
+ "unique_relevant_facts_by_hop": [
203
+ len(np.unique(edges[:, j])) for j in range(edges.shape[1])
204
+ ],
205
+ "within_split_majority_tail": majority_tail_diagnostics(rows),
206
+ "train_composite_majority_tail_fraction": (
207
+ float((rows[:, -1] == training_majority["target_token"]).mean())
208
+ if len(rows) and training_majority["target_token"] is not None
209
+ else None
210
+ ),
211
+ "suffix_without_head": suffix_target_diagnostics(rows),
212
+ }
213
+ return {
214
+ "interpretation": {
215
+ "atomic_coverage": "data availability only; does not establish model mastery",
216
+ "ood": "all facts are atomic training facts; none has composite-training experience",
217
+ "suffix": (
218
+ "empirical within-split target concentration; singleton suffixes score 1; "
219
+ "not a predictor, generalization bound, or evidence that the model ignores head"
220
+ ),
221
+ "majority": "within-split descriptive ceiling plus fixed training-majority fraction",
222
+ },
223
+ "atomic_facts": atomic_n,
224
+ "id_facts": int(id_facts.sum()),
225
+ "ood_facts": int((~id_facts).sum()),
226
+ "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()),
227
+ "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()),
228
+ "train_composite_fact_occurrence_counts": training_counts.tolist(),
229
+ "splits": per_split,
230
+ }
231
+
232
+
233
+ class _EpochStream:
234
+ """NumPy-only shuffled epochs, with the existing EpochStream draw convention."""
235
+
236
+ def __init__(self, size: int, seed):
237
+ self.size = size
238
+ self.rng = np.random.default_rng(seed)
239
+ self.remaining = np.empty(0, dtype=np.int64)
240
+
241
+ def take(self, n: int) -> np.ndarray:
242
+ if not n:
243
+ return np.empty(0, dtype=np.int64)
244
+ parts = []
245
+ while n:
246
+ if not len(self.remaining):
247
+ self.remaining = self.rng.permutation(self.size)
248
+ count = min(n, len(self.remaining))
249
+ parts.append(self.remaining[:count])
250
+ self.remaining = self.remaining[count:]
251
+ n -= count
252
+ return np.concatenate(parts)
253
+
254
+ def state_dict(self) -> dict:
255
+ return {
256
+ "size": self.size,
257
+ "rng": copy.deepcopy(self.rng.bit_generator.state),
258
+ "remaining": self.remaining.copy(),
259
+ }
260
+
261
+ def load_state_dict(self, state: dict):
262
+ if state["size"] != self.size:
263
+ raise ValueError("Epoch size mismatch")
264
+ remaining = np.asarray(state["remaining"])
265
+ if (
266
+ remaining.ndim != 1
267
+ or remaining.dtype != np.int64
268
+ or np.any((remaining < 0) | (remaining >= self.size))
269
+ or len(np.unique(remaining)) != len(remaining)
270
+ ):
271
+ raise ValueError("Invalid remaining epoch indices")
272
+ self.rng.bit_generator.state = copy.deepcopy(state["rng"])
273
+ self.remaining = remaining.copy()
274
+
275
+
276
+ class StratifiedStream:
277
+ """Fixed composition per batch over the table [atomics; train_composites].
278
+
279
+ Atomic, composite and interleaving draws use independent RNGs. Thus changing
280
+ phi or the composite pool cannot change the atomic sequence or its batch
281
+ positions. Individual strata use shuffled epochs and may cross an epoch
282
+ boundary within one batch. No evaluation data enters either stream.
283
+ """
284
+
285
+ def __init__(
286
+ self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int
287
+ ):
288
+ fields = {
289
+ "atomic_size": atomic_size,
290
+ "composite_size": composite_size,
291
+ "batch_size": batch_size,
292
+ "n_atomic": n_atomic,
293
+ }
294
+ for name, value in fields.items():
295
+ if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0:
296
+ raise ValueError(f"{name} must be a nonnegative integer")
297
+ if batch_size < 1 or n_atomic > batch_size:
298
+ raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size")
299
+ if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size):
300
+ raise ValueError("A sampled stratum cannot be empty")
301
+ self.atomic_size, self.composite_size = int(atomic_size), int(composite_size)
302
+ self.batch_size, self.n_atomic = int(batch_size), int(n_atomic)
303
+ self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101]))
304
+ self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102]))
305
+ self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103]))
306
+ self.batches = 0
307
+
308
+ def take(self, n: int | None = None) -> np.ndarray:
309
+ if n is not None and n != self.batch_size:
310
+ raise ValueError("StratifiedStream only emits its configured batch_size")
311
+ indices = np.r_[
312
+ self.atomic.take(self.n_atomic),
313
+ self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size,
314
+ ]
315
+ self.batches += 1
316
+ return indices[self.interleave.permutation(self.batch_size)]
317
+
318
+ def state_dict(self) -> dict:
319
+ return {
320
+ "version": 1,
321
+ "atomic_size": self.atomic_size,
322
+ "composite_size": self.composite_size,
323
+ "batch_size": self.batch_size,
324
+ "n_atomic": self.n_atomic,
325
+ "atomic": self.atomic.state_dict(),
326
+ "composite": self.composite.state_dict(),
327
+ "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state),
328
+ "batches": self.batches,
329
+ }
330
+
331
+ def load_state_dict(self, state: dict):
332
+ if state.get("version") != 1:
333
+ raise ValueError("Unsupported StratifiedStream state version")
334
+ for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"):
335
+ if state[name] != getattr(self, name):
336
+ raise ValueError(f"StratifiedStream {name} mismatch")
337
+ atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite)
338
+ interleave = copy.deepcopy(self.interleave)
339
+ atomic.load_state_dict(state["atomic"])
340
+ composite.load_state_dict(state["composite"])
341
+ interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"])
342
+ batches = state["batches"]
343
+ if not isinstance(batches, int) or batches < 0:
344
+ raise ValueError("Invalid completed batch count")
345
+ self.atomic, self.composite, self.interleave = atomic, composite, interleave
346
+ self.batches = batches
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prefix-only component interventions at every executed Transformer block.
2
+
3
+ The recipient block runs normally before mixing cached attention and MLP
4
+ increments at r1. The current block's MLP is never recomputed after mixing.
5
+ Only later blocks consume the intervention. Donors are graph-selected before
6
+ evaluating the model and receive only [head, r1] followed by fixed PAD tokens.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import time
14
+ from collections import Counter, defaultdict
15
+ from numbers import Integral
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch.nn import functional as F
20
+
21
+ from .grok_multihop import pack_rows
22
+
23
+ COMPONENTS = ("attention", "mlp", "both", "full")
24
+ SPLITS = ("test_composite", "test_full_composite", "ood_composite")
25
+ TRACE_FIELDS = ("input", "attention", "mlp", "residual")
26
+
27
+
28
+ def _choose(candidates, world_hash, seed, row, family):
29
+ if not candidates:
30
+ return None
31
+ material = json.dumps([world_hash, int(seed), list(map(int, row)), family])
32
+ index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates)
33
+ return sorted(candidates)[index]
34
+
35
+
36
+ def _path(head, relations, graph):
37
+ edges = []
38
+ for relation in relations:
39
+ fact = graph.get((int(head), int(relation)))
40
+ if fact is None:
41
+ return None
42
+ head, index = fact
43
+ edges.append(index)
44
+ return int(head), tuple(edges)
45
+
46
+
47
+ def select_donors(world, seed, split="test_composite"):
48
+ """Select same-r1 donors using only truth and split membership.
49
+
50
+ ID recipients and every donor-path fact are restricted to ID facts. OOD
51
+ recipients and donor paths analogously use only OOD facts. Different-bridge
52
+ paths must change the target and their complete queries must be untrained.
53
+ Same-bridge paths may be trained; their split is saved for separate scoring.
54
+ Rows without donors remain present with explicit masks and reasons.
55
+ """
56
+ if split not in SPLITS:
57
+ raise ValueError(f"split must be one of {SPLITS}")
58
+ rows = world[split]
59
+ n, hops = len(rows), rows.shape[1] - 2
60
+ if not 2 <= hops <= 4:
61
+ raise ValueError("Interventions require two-, three- or four-hop rows")
62
+ atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])}
63
+ atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic"
64
+ graph = {
65
+ (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)])
66
+ for h, r, t in world[atomic_split]
67
+ }
68
+ by_relation = defaultdict(list)
69
+ for (head, relation), (tail, _) in graph.items():
70
+ by_relation[relation].append((head, relation, tail))
71
+ training = {tuple(map(int, row[:-1])) for row in world["train_composite"]}
72
+ reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]}
73
+ result = {
74
+ "split": np.asarray(split),
75
+ "atomic_split": np.asarray(atomic_split),
76
+ "original_rows": rows.copy(),
77
+ "original_bridge": np.full(n, -1, dtype=np.int64),
78
+ "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64),
79
+ }
80
+ for family in ("different", "same"):
81
+ result.update(
82
+ {
83
+ family + "_donor": np.full((n, 3), -1, dtype=np.int64),
84
+ family + "_counterfactual_rows": np.full_like(rows, -1),
85
+ family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64),
86
+ family + "_valid": np.zeros(n, dtype=bool),
87
+ family + "_candidate_count": np.zeros(n, dtype=np.int64),
88
+ family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"),
89
+ family + "_counterfactual_split": np.full(n, "missing", dtype="U16"),
90
+ }
91
+ )
92
+ reasons = (
93
+ "same_head",
94
+ "same_bridge",
95
+ "missing_successor",
96
+ "same_target",
97
+ "head_is_answer",
98
+ "trained_counterfactual",
99
+ )
100
+ for reason in reasons:
101
+ result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64)
102
+ for i, row in enumerate(rows):
103
+ head, r1, target = int(row[0]), int(row[1]), int(row[-1])
104
+ original = _path(head, row[1:-1], graph)
105
+ if original is None or original[0] != target:
106
+ raise ValueError(f"Recipient is not a true all-{atomic_split} path")
107
+ bridge = graph[head, r1][0]
108
+ result["original_bridge"][i] = bridge
109
+ result["original_atomic_indices"][i] = original[1]
110
+ candidates = {"different": [], "same": []}
111
+ for dh, dr, db in by_relation[r1]:
112
+ continuation = _path(dh, row[1:-1], graph)
113
+ if continuation is None:
114
+ reason = "missing_successor"
115
+ else:
116
+ dt, edges = continuation
117
+ query = (dh, *map(int, row[1:-1]))
118
+ if dh != head and db == bridge and dh != target:
119
+ candidates["same"].append((dh, dr, db, dt, edges))
120
+ reason = (
121
+ "same_head"
122
+ if dh == head
123
+ else "same_bridge"
124
+ if db == bridge
125
+ else "same_target"
126
+ if dt == target
127
+ else "head_is_answer"
128
+ if dh in (target, dt)
129
+ else "trained_counterfactual"
130
+ if query in training
131
+ else None
132
+ )
133
+ if reason is None:
134
+ candidates["different"].append((dh, dr, db, dt, edges))
135
+ if reason:
136
+ result["different_rejected_" + reason][i] += 1
137
+ for family in ("different", "same"):
138
+ choices = candidates[family]
139
+ result[family + "_candidate_count"][i] = len(choices)
140
+ donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family)
141
+ if donor is None:
142
+ continue
143
+ dh, dr, db, dt, edges = donor
144
+ cf = (dh, *map(int, row[1:-1]), dt)
145
+ result[family + "_donor"][i] = dh, dr, db
146
+ result[family + "_counterfactual_rows"][i] = cf
147
+ result[family + "_atomic_indices"][i] = edges
148
+ result[family + "_valid"][i] = True
149
+ result[family + "_reason"][i] = "eligible"
150
+ result[family + "_counterfactual_split"][i] = (
151
+ "ood"
152
+ if split == "ood_composite"
153
+ else "train"
154
+ if cf[:-1] in training
155
+ else "reserved_test"
156
+ if cf[:-1] in reserved
157
+ else "unused"
158
+ )
159
+ return result
160
+
161
+
162
+ def executed_blocks(model):
163
+ return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks)
164
+
165
+
166
+ @torch.no_grad()
167
+ def traced_forward(
168
+ model,
169
+ tokens,
170
+ positions=None,
171
+ *,
172
+ patch_layer=None,
173
+ component="both",
174
+ donor_trace=None,
175
+ identity=False,
176
+ return_trace=False,
177
+ ):
178
+ """Run eval forward, optionally mixing one executed layer's r1 state.
179
+
180
+ Trace fields contain only position r1, with shape [batch, width]. For a
181
+ component patch the output is (recipient input + mixed A) + mixed M. Full
182
+ replacement also changes the incoming residual, so it equals replacing A
183
+ and M only at execution layer zero for same-r1 donors, not at later layers.
184
+ """
185
+ if model.training:
186
+ raise ValueError("Interventions require model.eval()")
187
+ blocks = executed_blocks(model)
188
+ if component not in COMPONENTS:
189
+ raise ValueError(f"component must be one of {COMPONENTS}")
190
+ if patch_layer is not None and (
191
+ isinstance(patch_layer, bool)
192
+ or not isinstance(patch_layer, Integral)
193
+ or not 0 <= patch_layer < len(blocks)
194
+ ):
195
+ raise ValueError("patch_layer must index an executed block")
196
+ if identity and donor_trace is not None:
197
+ raise ValueError("Identity and donor patches are mutually exclusive")
198
+ if (donor_trace is not None or identity) != (patch_layer is not None):
199
+ raise ValueError("A patch layer requires exactly one donor or identity patch")
200
+ if donor_trace is not None and len(donor_trace) != len(blocks):
201
+ raise ValueError("Donor trace must cover every executed layer")
202
+ if tokens.shape[1] < 2:
203
+ raise ValueError("The r1 position requires at least two tokens")
204
+ x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device))
205
+ trace = []
206
+ for layer, block in enumerate(blocks):
207
+ z = block.ln1(x)
208
+ batch, length, width = z.shape
209
+ attention = block.attention
210
+ q, k, v = (
211
+ attention.qkv(z)
212
+ .view(batch, length, 3, attention.heads, width // attention.heads)
213
+ .unbind(2)
214
+ )
215
+ a = F.scaled_dot_product_attention(
216
+ q.transpose(1, 2),
217
+ k.transpose(1, 2),
218
+ v.transpose(1, 2),
219
+ is_causal=True,
220
+ dropout_p=0.0,
221
+ )
222
+ a = attention.proj(a.transpose(1, 2).reshape(batch, length, width))
223
+ m = block.mlp(block.ln2(x + a))
224
+ residual = (x + a) + m
225
+ current = {
226
+ "input": x[:, 1].clone(),
227
+ "attention": a[:, 1].clone(),
228
+ "mlp": m[:, 1].clone(),
229
+ "residual": residual[:, 1].clone(),
230
+ }
231
+ if return_trace:
232
+ trace.append(current)
233
+ if layer == patch_layer:
234
+ donor = current if identity else donor_trace[layer]
235
+ if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS):
236
+ raise ValueError("Donor trace has incompatible batch or width")
237
+ if component == "full":
238
+ replacement = donor["residual"]
239
+ else:
240
+ mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1]
241
+ mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1]
242
+ replacement = (x[:, 1] + mixed_a) + mixed_m
243
+ residual = residual.clone()
244
+ residual[:, 1] = replacement
245
+ x = residual
246
+ x = model.ln_final(x)
247
+ if positions is not None:
248
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
249
+ logits = F.linear(x, model.token.weight)
250
+ return (logits, trace) if return_trace else logits
251
+
252
+
253
+ @torch.no_grad()
254
+ def prefix_trace(model, prefixes, padded_length):
255
+ """Evaluate only two supplied tokens and a fixed zero suffix; never a target."""
256
+ if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4:
257
+ raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length")
258
+ tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device)
259
+ tokens[:, :2] = prefixes
260
+ positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device)
261
+ return traced_forward(model, tokens, positions, return_trace=True)[1]
262
+
263
+
264
+ @torch.no_grad()
265
+ def evaluate_condition(
266
+ model,
267
+ rows,
268
+ device,
269
+ padded_length,
270
+ *,
271
+ donor_prefixes=None,
272
+ patch_layer=None,
273
+ component="both",
274
+ identity=False,
275
+ batch_size=1024,
276
+ verify_trace=False,
277
+ ):
278
+ """Generate answer then EOS, reapplying exactly the same donor intervention."""
279
+ if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2):
280
+ raise ValueError("Donor prefixes must align one-to-one with recipient rows")
281
+ answers, stops, logits_saved = [], [], []
282
+ max_delta = prefix_delta = 0.0
283
+ packed = pack_rows(rows, padded_length)
284
+ for start in range(0, len(rows), batch_size):
285
+ x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed)
286
+ x = x.clone()
287
+ donor = None
288
+ if donor_prefixes is not None:
289
+ prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device)
290
+ donor = prefix_trace(model, prefixes, padded_length)
291
+ arguments = dict(
292
+ patch_layer=patch_layer,
293
+ component=component,
294
+ donor_trace=donor,
295
+ identity=identity,
296
+ )
297
+ logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments)
298
+ if verify_trace:
299
+ if patch_layer is not None:
300
+ raise ValueError("Native-forward verification applies to baseline only")
301
+ reference = model(x, pos)
302
+ max_delta = max(max_delta, float((reference - logits).abs().max()))
303
+ if not torch.equal(reference.argmax(-1), logits.argmax(-1)):
304
+ raise AssertionError("Traced forward changes native argmax")
305
+ prefix = prefix_trace(model, x[:, :2], padded_length)
306
+ for full, truncated in zip(trace, prefix, strict=True):
307
+ for field in TRACE_FIELDS:
308
+ prefix_delta = max(
309
+ prefix_delta, float((full[field] - truncated[field]).abs().max())
310
+ )
311
+ answer = logits[:, 0].argmax(-1)
312
+ logits_saved.append(logits[:, 0].cpu().numpy())
313
+ x[torch.arange(len(x), device=device), pos[:, 1]] = answer
314
+ continuation = traced_forward(model, x, pos, **arguments)
315
+ if verify_trace:
316
+ reference = model(x, pos)
317
+ max_delta = max(max_delta, float((reference - continuation).abs().max()))
318
+ if not torch.equal(reference.argmax(-1), continuation.argmax(-1)):
319
+ raise AssertionError("Generated-answer trace changes native argmax")
320
+ answers.append(answer.cpu().numpy())
321
+ stops.append(continuation[:, 1].argmax(-1).cpu().numpy())
322
+ if max_delta > 1e-5 or prefix_delta > 1e-5:
323
+ raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}")
324
+ return {
325
+ "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64),
326
+ "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64),
327
+ "answer_logits": np.concatenate(logits_saved)
328
+ if logits_saved
329
+ else np.empty((0, model.token.num_embeddings), dtype=np.float32),
330
+ }, {
331
+ "native_comparison_performed": verify_trace,
332
+ "native_max_logit_delta": max_delta,
333
+ "prefix_only_vs_full_all_layers_max_delta": prefix_delta,
334
+ }
335
+
336
+
337
+ def _metrics(arrays, condition, selected, original, target, baseline):
338
+ mask = selected & arrays[condition + "_valid"]
339
+ n, total = int(mask.sum()), len(mask)
340
+ answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"]
341
+
342
+ def mean(value):
343
+ return float(value[mask].mean()) if n else None
344
+
345
+ return {
346
+ "n": n,
347
+ "total_n": total,
348
+ "coverage": n / total if total else None,
349
+ "target_answer_accuracy": mean(answer == target),
350
+ "target_complete_accuracy": mean((answer == target) & (stop == 1)),
351
+ "original_answer_accuracy": mean(answer == original),
352
+ "original_complete_accuracy": mean((answer == original) & (stop == 1)),
353
+ "other_answer_rate": mean((answer != target) & (answer != original)),
354
+ "eos_accuracy": mean(stop == 1),
355
+ "answer_change_rate": mean(answer != baseline),
356
+ }
357
+
358
+
359
+ def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024):
360
+ """Evaluate every executed layer, preserving all rows and prerequisite masks."""
361
+ started = time.perf_counter()
362
+ model.eval()
363
+ split = str(donors["split"].item())
364
+ rows = world[split]
365
+ if not np.array_equal(rows, donors["original_rows"]):
366
+ raise ValueError("Donor rows differ from the registered evaluation split")
367
+ n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2
368
+ arrays = {key: value.copy() for key, value in donors.items()}
369
+ all_rows = np.ones(n, dtype=bool)
370
+ conditions, audits = {}, {}
371
+
372
+ def evaluate(name, mask, inputs, *, family=None, **kwargs):
373
+ result, audit = evaluate_condition(
374
+ model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs
375
+ )
376
+ for key in ("answer", "stop"):
377
+ values = np.full(n, -1, dtype=np.int64)
378
+ values[mask] = result[key]
379
+ arrays[name + "_" + key] = values
380
+ arrays[name + "_valid"] = mask.copy()
381
+ targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1]
382
+ for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)):
383
+ values = np.full(n, np.nan, dtype=np.float32)
384
+ values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]]
385
+ arrays[name + "_" + suffix] = values
386
+ conditions[name] = {
387
+ "family": family,
388
+ **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")},
389
+ }
390
+ audits[name] = audit
391
+
392
+ evaluate("baseline", all_rows, rows, verify_trace=True)
393
+ for family in ("different", "same"):
394
+ valid = donors[family + "_valid"]
395
+ # Match batch shape as well as sequence shape for floating-point controls.
396
+ evaluate(family + "_matched_baseline", valid, rows, family=family)
397
+ evaluate(
398
+ family + "_counterfactual_input",
399
+ valid,
400
+ donors[family + "_counterfactual_rows"],
401
+ family=family,
402
+ )
403
+ blocks = executed_blocks(model)
404
+ for layer in range(len(blocks)):
405
+ for component in COMPONENTS:
406
+ identity_name = f"e{layer:03d}_identity_{component}"
407
+ evaluate(
408
+ identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True
409
+ )
410
+ for key in ("answer", "stop", "original_logit", "target_logit"):
411
+ if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]):
412
+ raise AssertionError(f"Identity patch changes {identity_name}.{key}")
413
+ for family in ("different", "same"):
414
+ valid = donors[family + "_valid"]
415
+ name = f"e{layer:03d}_{family}_{component}"
416
+ evaluate(
417
+ name,
418
+ valid,
419
+ rows,
420
+ family=family,
421
+ patch_layer=layer,
422
+ component=component,
423
+ donor_prefixes=donors[family + "_donor"][valid, :2],
424
+ )
425
+ if layer == len(blocks) - 1:
426
+ for key in ("answer", "stop", "original_logit"):
427
+ if not np.array_equal(
428
+ arrays[name + "_" + key][valid],
429
+ arrays[family + "_matched_baseline_" + key][valid],
430
+ ):
431
+ raise AssertionError("Last-block r1 patch changes later answer/EOS")
432
+ if layer == 0:
433
+ for family in ("different", "same"):
434
+ valid = donors[family + "_valid"]
435
+ for key in ("answer", "stop", "original_logit", "target_logit"):
436
+ left = arrays[f"e000_{family}_both_{key}"][valid]
437
+ right = arrays[f"e000_{family}_full_{key}"][valid]
438
+ if not np.array_equal(left, right):
439
+ raise AssertionError("First-layer same-r1 both/full differ")
440
+ atomics, _ = evaluate_condition(
441
+ model, world["atomic"], device, padded_length, batch_size=batch_size
442
+ )
443
+ atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1)
444
+ arrays["atomic_rows"] = world["atomic"].copy()
445
+ arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"]
446
+ groups = {"all_rows": all_rows}
447
+ prerequisites = {}
448
+ for family in ("original", "different", "same"):
449
+ valid = all_rows if family == "original" else donors[family + "_valid"]
450
+ indices = donors[family + "_atomic_indices"]
451
+ correct = np.zeros_like(indices, dtype=bool)
452
+ correct[valid] = atom_correct[indices[valid]]
453
+ arrays[family + "_atomic_complete_correct"] = correct
454
+ complete = valid & correct.all(axis=1)
455
+ groups[family + "_all_atomic_correct"] = complete
456
+ prerequisites[family] = {
457
+ "n": int(valid.sum()),
458
+ "total_n": n,
459
+ "coverage": float(valid.mean()) if n else None,
460
+ "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None,
461
+ "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist()
462
+ if valid.any()
463
+ else None,
464
+ }
465
+ for family in ("different", "same"):
466
+ valid = donors[family + "_valid"]
467
+ baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & (
468
+ arrays[family + "_matched_baseline_stop"] == 1
469
+ )
470
+ groups[family + "_donor_available"] = valid
471
+ groups[family + "_donor_missing"] = ~valid
472
+ cf = family + "_counterfactual_input"
473
+ cf_correct = valid & (
474
+ arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1]
475
+ )
476
+ cf_correct &= arrays[cf + "_stop"] == 1
477
+ groups[family + "_native_original_and_counterfactual_correct"] = (
478
+ baseline_correct & cf_correct
479
+ )
480
+ for category in ("train", "reserved_test", "unused", "ood"):
481
+ groups[family + "_counterfactual_" + category] = valid & (
482
+ donors[family + "_counterfactual_split"] == category
483
+ )
484
+ scores = {}
485
+ for group, mask in groups.items():
486
+ arrays["subset_" + group] = mask.copy()
487
+ scored = {}
488
+ for condition, description in conditions.items():
489
+ family = description["family"]
490
+ target = (
491
+ rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1]
492
+ )
493
+ scored[condition] = _metrics(
494
+ arrays,
495
+ condition,
496
+ mask,
497
+ rows[:, -1],
498
+ target,
499
+ arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"],
500
+ )
501
+ scores[group] = {
502
+ "n": int(mask.sum()),
503
+ "total_n": n,
504
+ "coverage": float(mask.mean()) if n else None,
505
+ "conditions": scored,
506
+ }
507
+ return {
508
+ "split": split,
509
+ "atomic_split": str(donors["atomic_split"].item()),
510
+ "sample_rule": "training-independent fixed probe"
511
+ if split == "test_composite"
512
+ else "full split",
513
+ "hops": padded_length - 2,
514
+ "executed_depth": len(blocks),
515
+ "unique_layers": len(model.blocks),
516
+ "repeats": getattr(model, "repeats", 1),
517
+ "patch_position": 1,
518
+ "conditions": conditions,
519
+ "scores": scores,
520
+ "atomic_preconditions": prerequisites,
521
+ "donor_coverage": {
522
+ family: {
523
+ "n": int(donors[family + "_valid"].sum()),
524
+ "total_n": n,
525
+ "reasons": dict(Counter(donors[family + "_reason"].tolist())),
526
+ "counterfactual_split": dict(
527
+ Counter(donors[family + "_counterfactual_split"].tolist())
528
+ ),
529
+ }
530
+ for family in ("different", "same")
531
+ },
532
+ "engineering_checks": {
533
+ "native_trace": audits["baseline"],
534
+ "identity_all_layers_components": True,
535
+ "first_layer_same_r1_both_equals_full": True,
536
+ "last_layer_r1_patch_cannot_change_later_answer_or_eos": True,
537
+ "donor_nonpadding_tokens": 2,
538
+ "donor_padded_length": padded_length,
539
+ "mlp_recomputed_after_mixing": False,
540
+ "eos_uses_generated_answer_and_reapplies_same_patch": True,
541
+ },
542
+ "interpretation": (
543
+ "End-to-end prefix-state interventions, not proof that facts reside only in MLP. "
544
+ "Component mixtures retain recipient incoming residual. Both/full are equivalent "
545
+ "only at first execution layer with same r1; later differences are expected. "
546
+ "Facts and queries within one world are not independent experimental worlds."
547
+ ),
548
+ "evaluation_seconds": time.perf_counter() - started,
549
+ }, arrays
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_model.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Depth-shared GPT blocks for controlled composition-learning comparisons.
2
+
3
+ This keeps the existing SmallGPT tokenization, causal attention, dropout and tied
4
+ readout. ``config.layers`` counts independently parameterized blocks; each loop
5
+ executes this whole block group. Positions and token embeddings are added once.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from dataclasses import replace
12
+ from numbers import Integral
13
+
14
+ import torch
15
+ from torch.nn import functional as F
16
+
17
+ from .bios_model import matmul_flops
18
+ from .grok_depth import SmallGPT
19
+
20
+ INITIALIZATIONS = frozenset({"legacy_unique", "scaled_effective", "zero_residual"})
21
+
22
+
23
+ def _positive_integer(value, name):
24
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < 1:
25
+ raise ValueError(f"{name} must be a positive integer, got {value!r}")
26
+ return int(value)
27
+
28
+
29
+ class LoopGPT(SmallGPT):
30
+ """Vanilla fixed-loop Transformer with shared attention, MLP and block norms.
31
+
32
+ ``legacy_unique`` reproduces SmallGPT's residual initialization based on the
33
+ number of unique blocks. ``scaled_effective`` scales residual output weights
34
+ by the total executed depth; ``zero_residual`` instead zeros those weights.
35
+ Embeddings, other projections and all biases retain SmallGPT initialization.
36
+
37
+ Changing ``repeats`` in forward does not change parameter initialization. It
38
+ is a computation-depth intervention, not an independently initialized model.
39
+ Save repeats, dropout and initialization alongside ``config_dict()`` and the
40
+ state dict when constructing checkpoints; they are architectural metadata.
41
+ """
42
+
43
+ def __init__(self, config, repeats=1, dropout=0.1, initialization="scaled_effective"):
44
+ repeats = _positive_integer(repeats, "repeats")
45
+ _positive_integer(config.layers, "config.layers")
46
+ if initialization not in INITIALIZATIONS:
47
+ raise ValueError(f"initialization must be one of {sorted(INITIALIZATIONS)}")
48
+ super().__init__(config, dropout=dropout)
49
+ self.repeats = repeats
50
+ self.initialization = initialization
51
+ with torch.no_grad():
52
+ for block in self.blocks:
53
+ for module in (block.attention.proj, block.mlp.down):
54
+ if initialization == "scaled_effective":
55
+ module.weight.div_(math.sqrt(repeats))
56
+ elif initialization == "zero_residual":
57
+ module.weight.zero_()
58
+
59
+ @property
60
+ def effective_depth(self):
61
+ return self.config.layers * self.repeats
62
+
63
+ def iter_blocks(self, repeats=None):
64
+ """Yield executed blocks; repeated occurrences are the same module object."""
65
+ count = self.repeats if repeats is None else _positive_integer(repeats, "repeats")
66
+ for _ in range(count):
67
+ yield from self.blocks
68
+
69
+ def forward(self, tokens, positions=None, repeats=None):
70
+ p = self.dropout if self.training else 0.0
71
+ x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
72
+ x = F.dropout(x, p=p, training=self.training)
73
+ for block in self.iter_blocks(repeats):
74
+ z = block.ln1(x)
75
+ batch, length, width = z.shape
76
+ a = block.attention
77
+ q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
78
+ y = F.scaled_dot_product_attention(
79
+ q.transpose(1, 2),
80
+ k.transpose(1, 2),
81
+ v.transpose(1, 2),
82
+ is_causal=True,
83
+ dropout_p=p,
84
+ )
85
+ y = a.proj(y.transpose(1, 2).reshape(batch, length, width))
86
+ x = x + F.dropout(y, p=p, training=self.training)
87
+ x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training)
88
+ x = self.ln_final(x)
89
+ if positions is not None:
90
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
91
+ return F.linear(x, self.token.weight)
92
+
93
+
94
+ def flops(config, repeats, batch, sequence, output_positions=2, backward=True):
95
+ """Estimate matmul FLOPs using executed blocks, counting the readout once.
96
+
97
+ Uses the same executed-shape estimate as bios_model.matmul_flops. Excludes
98
+ elementwise operations and uses three forward equivalents for training.
99
+ """
100
+ count = _positive_integer(repeats, "repeats")
101
+ layers = _positive_integer(config.layers, "config.layers")
102
+ return matmul_flops(
103
+ replace(config, layers=layers * count),
104
+ batch,
105
+ sequence,
106
+ output_positions=output_positions,
107
+ backward=backward,
108
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Graph-only, exposure-matched same-bridge donors for two-hop OOD queries.
2
+
3
+ Every donor contains only [head, r1]; its bridge is saved as truth, never fed
4
+ to the model. ID donors must have actually occurred at the first position of
5
+ composite training. OOD donors have zero composite exposure at either position.
6
+ All eligible donors and ID x OOD pairs are retained. A pair is a repeated
7
+ measurement of its recipient, not an independent query or world.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ from collections import defaultdict
15
+ from collections.abc import Mapping
16
+ from numbers import Integral
17
+
18
+ import numpy as np
19
+
20
+ from .grok_multihop_data import audit_world, path_details
21
+
22
+
23
+ def _nonnegative_integer(value, name):
24
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < 0:
25
+ raise ValueError(f"{name} must be a nonnegative integer")
26
+ return int(value)
27
+
28
+
29
+ def _exposure_spec(world, run_metadata, steps):
30
+ spec = run_metadata.get("spec", run_metadata)
31
+ if not isinstance(spec, Mapping):
32
+ raise ValueError("Run metadata must contain a specification mapping")
33
+ count = _nonnegative_integer(spec["steps"] if steps is None else steps, "steps")
34
+ if count > _nonnegative_integer(spec["steps"], "registered steps"):
35
+ raise ValueError("Exposure cannot exceed the registered training endpoint")
36
+ batch = _nonnegative_integer(spec["batch_size"], "batch_size")
37
+ atomic_batch = _nonnegative_integer(spec["n_atomic_per_batch"], "n_atomic_per_batch")
38
+ seed = _nonnegative_integer(spec["stream_seed"], "stream_seed")
39
+ if batch < 1 or atomic_batch > batch:
40
+ raise ValueError("Require batch_size > 0 and n_atomic_per_batch <= batch_size")
41
+ for key in ("world_seed", "hops"):
42
+ expected = world["metadata"]["seed" if key == "world_seed" else key]
43
+ if key in spec and spec[key] != expected:
44
+ raise ValueError(f"Run specification disagrees with the world: {key}")
45
+ return {
46
+ "dataset_sha256": world["metadata"]["dataset_sha256"],
47
+ "stream_seed": seed,
48
+ "steps": count,
49
+ "batch_size": batch,
50
+ "n_atomic_per_batch": atomic_batch,
51
+ "atomic_size": len(world["atomic"]),
52
+ "composite_size": len(world["train_composite"]),
53
+ "stream": "StratifiedStream independent shuffled epochs v1",
54
+ }
55
+
56
+
57
+ def _cache_key(spec):
58
+ return hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest()
59
+
60
+
61
+ def _record_exposures(size, draws, seed, tag):
62
+ """Replay the final partial epoch without materializing the full sample stream."""
63
+ if not size:
64
+ if draws:
65
+ raise ValueError("A sampled training stratum cannot be empty")
66
+ return np.empty(0, dtype=np.int64)
67
+ complete, remainder = divmod(draws, size)
68
+ counts = np.full(size, complete, dtype=np.int64)
69
+ if remainder:
70
+ rng = np.random.default_rng(np.random.SeedSequence([seed, tag]))
71
+ for _ in range(complete):
72
+ rng.permutation(size)
73
+ counts[rng.permutation(size)[:remainder]] += 1
74
+ return counts
75
+
76
+
77
+ def actual_exposure_counts(world, run_metadata, *, steps=None):
78
+ """Count actual atomic and composite records sampled through a fixed step.
79
+
80
+ The training sampler has independent atomic/composite RNG streams, so its
81
+ interleaving draws do not change these counts. Full epochs expose every
82
+ record once; only the final partial epoch needs its exact permutation.
83
+ ``cache_key`` depends on data, sample-stream seed, step and batch mixture,
84
+ but not architecture or initialization, which do not change this sampler.
85
+ """
86
+ checked = audit_world(world)
87
+ if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"):
88
+ raise ValueError("World metadata hash does not match the data")
89
+ if world["metadata"]["hops"] != 2:
90
+ raise ValueError("Same-bridge exposure comparison requires two-hop worlds")
91
+ spec = _exposure_spec(world, run_metadata, steps)
92
+ atom_count = _record_exposures(
93
+ spec["atomic_size"],
94
+ spec["steps"] * spec["n_atomic_per_batch"],
95
+ spec["stream_seed"],
96
+ 145101,
97
+ )
98
+ composite_count = _record_exposures(
99
+ spec["composite_size"],
100
+ spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]),
101
+ spec["stream_seed"],
102
+ 145102,
103
+ )
104
+ _, edges = path_details(
105
+ world["train_composite"],
106
+ world["atomic"],
107
+ world["metadata"]["entities"],
108
+ world["metadata"]["relations"],
109
+ )
110
+ table = np.zeros((len(world["atomic"]), 2), dtype=np.int64)
111
+ actual = np.zeros_like(table)
112
+ for position in range(2):
113
+ np.add.at(table[:, position], edges[:, position], 1)
114
+ np.add.at(actual[:, position], edges[:, position], composite_count)
115
+ return {
116
+ "cache_key": _cache_key(spec),
117
+ "cache_spec": spec,
118
+ "atomic_record_counts": atom_count,
119
+ "composite_record_counts": composite_count,
120
+ "table_position_counts": table,
121
+ "actual_position_counts": actual,
122
+ }
123
+
124
+
125
+ def _rows(values, columns):
126
+ return np.asarray(values, dtype=np.int64).reshape(-1, columns)
127
+
128
+
129
+ def select_same_bridge_donors(world, run_metadata, *, steps=None, exposure=None):
130
+ """Enumerate same-r1/same-bridge ID and OOD donors without model selection.
131
+
132
+ Inputs are a standard audited loop world and either run metadata with a
133
+ ``spec`` field or the specification directly. All original OOD rows stay
134
+ aligned with validity masks and explicit reasons. Flattened donor arrays
135
+ include recipients with only one donor class. Main pairs require both.
136
+ ``exposure`` may cache ``actual_exposure_counts`` for a shared sample stream.
137
+
138
+ For pair-level scores, first average pairs within each recipient (using
139
+ pair_weights), then average recipients. Pair weights sum to one for each
140
+ common recipient; they do not sum to one across the whole world.
141
+ """
142
+ checked = audit_world(world)
143
+ if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"):
144
+ raise ValueError("World metadata hash does not match the data")
145
+ if world["metadata"]["hops"] != 2:
146
+ raise ValueError("Same-bridge selection requires two-hop worlds")
147
+ spec = _exposure_spec(world, run_metadata, steps)
148
+ exposure = (
149
+ actual_exposure_counts(world, run_metadata, steps=steps) if exposure is None else exposure
150
+ )
151
+ if exposure.get("cache_key") != _cache_key(spec) or exposure.get("cache_spec") != spec:
152
+ raise ValueError("Cached exposure belongs to another world or sample stream")
153
+ atoms = world["atomic"]
154
+ position_counts = np.asarray(exposure["actual_position_counts"])
155
+ table_counts = np.asarray(exposure["table_position_counts"])
156
+ if (
157
+ position_counts.shape != (len(atoms), 2)
158
+ or table_counts.shape != position_counts.shape
159
+ or position_counts.dtype != np.int64
160
+ or table_counts.dtype != np.int64
161
+ or (position_counts < 0).any()
162
+ or (table_counts < 0).any()
163
+ ):
164
+ raise ValueError("Cached position exposure counts have invalid shape or values")
165
+ atom_index = {tuple(map(int, row)): i for i, row in enumerate(atoms)}
166
+ is_id = np.zeros(len(atoms), dtype=bool)
167
+ is_id[[atom_index[tuple(map(int, row))] for row in world["id_atomic"]]] = True
168
+ if position_counts[~is_id].any() or table_counts[~is_id].any():
169
+ raise ValueError("An OOD fact has composite training exposure")
170
+ expected_draws = spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"])
171
+ if not np.array_equal(position_counts.sum(axis=0), [expected_draws, expected_draws]):
172
+ raise ValueError("Cached position counts disagree with the registered sample budget")
173
+ incoming = defaultdict(list)
174
+ for i, (head, relation, bridge) in enumerate(atoms):
175
+ incoming[int(relation), int(bridge)].append((int(head), i))
176
+ for candidates in incoming.values():
177
+ candidates.sort()
178
+ original = world["ood_composite"]
179
+ nodes, edges = path_details(
180
+ original, atoms, world["metadata"]["entities"], world["metadata"]["relations"]
181
+ )
182
+ if is_id[edges].any():
183
+ raise ValueError("Recipients must contain only OOD facts")
184
+ n = len(original)
185
+ id_indices, ood_indices = [], []
186
+ id_recipient, ood_recipient = [], []
187
+ id_offsets, ood_offsets = [0], [0]
188
+ second_only = np.zeros(n, dtype=np.int64)
189
+ nominal_unexposed = np.zeros(n, dtype=np.int64)
190
+ rejected_same_head = np.zeros(n, dtype=np.int64)
191
+ rejected_answer_head = np.zeros(n, dtype=np.int64)
192
+ for i, (head, r1, _r2, target) in enumerate(original):
193
+ for donor_head, fact in incoming[int(r1), int(nodes[i, 1])]:
194
+ if donor_head == head:
195
+ rejected_same_head[i] += 1
196
+ continue
197
+ if donor_head == target:
198
+ rejected_answer_head[i] += 1
199
+ continue
200
+ if is_id[fact]:
201
+ if position_counts[fact, 0] > 0:
202
+ id_indices.append(fact)
203
+ id_recipient.append(i)
204
+ elif position_counts[fact, 1] > 0:
205
+ second_only[i] += 1
206
+ else:
207
+ nominal_unexposed[i] += 1
208
+ else:
209
+ ood_indices.append(fact)
210
+ ood_recipient.append(i)
211
+ id_offsets.append(len(id_indices))
212
+ ood_offsets.append(len(ood_indices))
213
+ id_offsets = np.asarray(id_offsets, dtype=np.int64)
214
+ ood_offsets = np.asarray(ood_offsets, dtype=np.int64)
215
+ id_count, ood_count = np.diff(id_offsets), np.diff(ood_offsets)
216
+ valid = (id_count > 0) & (ood_count > 0)
217
+ pair_recipient, pair_id, pair_ood, weights = [], [], [], []
218
+ for i in np.flatnonzero(valid):
219
+ weight = 1.0 / int(id_count[i] * ood_count[i])
220
+ for j in range(id_offsets[i], id_offsets[i + 1]):
221
+ for k in range(ood_offsets[i], ood_offsets[i + 1]):
222
+ pair_recipient.append(i)
223
+ pair_id.append(j)
224
+ pair_ood.append(k)
225
+ weights.append(weight)
226
+ pair_recipient = np.asarray(pair_recipient, dtype=np.int64)
227
+ pair_id = np.asarray(pair_id, dtype=np.int64)
228
+ pair_ood = np.asarray(pair_ood, dtype=np.int64)
229
+ id_indices = np.asarray(id_indices, dtype=np.int64)
230
+ ood_indices = np.asarray(ood_indices, dtype=np.int64)
231
+ reason = np.full(n, "eligible", dtype="U40")
232
+ reason[(id_count == 0) & (ood_count > 0)] = "no_id_first_position_donor"
233
+ reason[(id_count > 0) & (ood_count == 0)] = "no_other_ood_donor"
234
+ reason[(id_count == 0) & (ood_count == 0)] = "no_id_or_other_ood_donor"
235
+ result = {
236
+ "original_rows": original.copy(),
237
+ "original_bridge": nodes[:, 1].copy(),
238
+ "original_atomic_indices": edges.copy(),
239
+ "original_prefix_contains_answer": original[:, 0] == original[:, -1],
240
+ "original_answer_equals_bridge": nodes[:, 1] == original[:, -1],
241
+ "common_valid": valid,
242
+ "reason": reason,
243
+ "id_candidate_count": id_count,
244
+ "ood_candidate_count": ood_count,
245
+ "id_second_only_candidate_count": second_only,
246
+ "id_unexposed_candidate_count": nominal_unexposed,
247
+ "rejected_same_head_count": rejected_same_head,
248
+ "rejected_answer_head_count": rejected_answer_head,
249
+ "id_candidate_offsets": id_offsets,
250
+ "ood_candidate_offsets": ood_offsets,
251
+ "id_donor_atomic_indices": id_indices,
252
+ "ood_donor_atomic_indices": ood_indices,
253
+ "id_donor_rows": atoms[id_indices].copy(),
254
+ "ood_donor_rows": atoms[ood_indices].copy(),
255
+ "id_recipient_indices": np.asarray(id_recipient, dtype=np.int64),
256
+ "ood_recipient_indices": np.asarray(ood_recipient, dtype=np.int64),
257
+ "pair_recipient_indices": pair_recipient,
258
+ "pair_rows": original[pair_recipient].copy(),
259
+ "pair_id_indices": pair_id,
260
+ "pair_ood_indices": pair_ood,
261
+ "pair_weights": np.asarray(weights, dtype=np.float64),
262
+ "pair_id_donor_rows": atoms[id_indices[pair_id]].copy(),
263
+ "pair_ood_donor_rows": atoms[ood_indices[pair_ood]].copy(),
264
+ "pair_self_donor_rows": atoms[edges[pair_recipient, 0]].copy(),
265
+ "atomic_is_id": is_id,
266
+ "atomic_single_training_exposure": np.asarray(exposure["atomic_record_counts"]).copy(),
267
+ "atomic_composite_table_position_counts": table_counts.copy(),
268
+ "atomic_composite_actual_position_exposure": position_counts.copy(),
269
+ "composite_record_training_exposure": np.asarray(
270
+ exposure["composite_record_counts"]
271
+ ).copy(),
272
+ }
273
+ trained = {tuple(map(int, row[:-1])) for row in world["train_composite"]}
274
+ for family in ("id", "ood"):
275
+ cf = result["pair_rows"].copy()
276
+ cf[:, 0] = result["pair_" + family + "_donor_rows"][:, 0]
277
+ _, cf_edges = path_details(
278
+ cf, atoms, world["metadata"]["entities"], world["metadata"]["relations"]
279
+ )
280
+ if any(tuple(map(int, row[:-1])) in trained for row in cf):
281
+ raise ValueError("A same-bridge counterfactual query was used in training")
282
+ if is_id[cf_edges[:, 1]].any():
283
+ raise ValueError("A donor has changed the recipient's OOD successor")
284
+ result["pair_" + family + "_counterfactual_rows"] = cf
285
+ result["pair_" + family + "_counterfactual_atomic_indices"] = cf_edges
286
+ result["pair_" + family + "_counterfactual_split"] = np.full(
287
+ len(cf), "mixed_id_ood" if family == "id" else "pure_ood", dtype="U16"
288
+ )
289
+ result["audit"] = {
290
+ "dataset_sha256": checked["dataset_sha256"],
291
+ "exposure_cache_key": exposure["cache_key"],
292
+ "exposure_cache_spec": spec,
293
+ "recipient_split": "ood_composite",
294
+ "selection": "enumerate all graph-qualified ID x OOD pairs; no model-based selection",
295
+ "id_requirement": "same r1/bridge, different head, actual first-position exposure > 0",
296
+ "ood_requirement": (
297
+ "same r1/bridge, different head, no composite exposure at either position"
298
+ ),
299
+ "answer_head_excluded": True,
300
+ "prefix_inputs": "donor_rows[:, :2]; bridge is audit truth, never model input",
301
+ "successor": "unchanged OOD second fact for both donor classes",
302
+ "all_recipient_n": n,
303
+ "id_available_n": int((id_count > 0).sum()),
304
+ "ood_available_n": int((ood_count > 0).sum()),
305
+ "common_n": int(valid.sum()),
306
+ "common_fraction": float(valid.mean()) if n else None,
307
+ "pair_n": len(pair_recipient),
308
+ "unique_original_first_facts_n": len(np.unique(edges[:, 0])),
309
+ "unique_original_second_facts_n": len(np.unique(edges[:, 1])),
310
+ "unique_common_first_facts_n": len(np.unique(edges[valid, 0])),
311
+ "unique_common_second_facts_n": len(np.unique(edges[valid, 1])),
312
+ "unique_common_id_donor_facts_n": len(np.unique(id_indices[pair_id])),
313
+ "unique_common_ood_donor_facts_n": len(np.unique(ood_indices[pair_ood])),
314
+ "unique_all_id_donor_facts_n": len(np.unique(id_indices)),
315
+ "unique_all_ood_donor_facts_n": len(np.unique(ood_indices)),
316
+ "unique_common_r1_bridge_groups_n": len(
317
+ np.unique(np.c_[original[valid, 1], nodes[valid, 1]], axis=0)
318
+ ),
319
+ "original_prefix_contains_answer_n": int(result["original_prefix_contains_answer"].sum()),
320
+ "common_prefix_contains_answer_n": int(
321
+ result["original_prefix_contains_answer"][valid].sum()
322
+ ),
323
+ "original_answer_equals_bridge_n": int(result["original_answer_equals_bridge"].sum()),
324
+ "common_answer_equals_bridge_n": int(result["original_answer_equals_bridge"][valid].sum()),
325
+ "common_first_edge_self_loop_n": int((original[valid, 0] == nodes[valid, 1]).sum()),
326
+ "common_id_donor_prefix_contains_answer_n": int(
327
+ (result["pair_id_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum()
328
+ ),
329
+ "common_ood_donor_prefix_contains_answer_n": int(
330
+ (result["pair_ood_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum()
331
+ ),
332
+ "id_second_only_candidate_n": int(second_only.sum()),
333
+ "id_unexposed_candidate_n": int(nominal_unexposed.sum()),
334
+ "missing_reasons": {
335
+ str(value): int((reason == value).sum()) for value in np.unique(reason)
336
+ },
337
+ "aggregation": (
338
+ "mean pairs per recipient, recipients per model, "
339
+ "initializations per world, worlds equally"
340
+ ),
341
+ }
342
+ return result
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Same-bridge prefix interventions, with query-balanced donor summaries.
2
+
3
+ The donor selector never sees model scores. This evaluator reuses the audited
4
+ first-block component mixer; it does not retrain models or recompute the current
5
+ MLP after mixing. All candidate donors are evaluated, then averaged within the
6
+ recipient query before any world-level aggregation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import time
13
+
14
+ import numpy as np
15
+ import torch
16
+
17
+ from .grok_loop_mechanism import COMPONENTS, evaluate_condition, executed_blocks
18
+
19
+ METRICS = (
20
+ "answer_accuracy",
21
+ "complete_accuracy",
22
+ "eos_accuracy",
23
+ "target_probability",
24
+ "target_log_probability",
25
+ "target_margin",
26
+ )
27
+
28
+
29
+ def state_digest(model):
30
+ digest = hashlib.sha256()
31
+ for name, tensor in sorted(model.state_dict().items()):
32
+ digest.update(name.encode())
33
+ value = tensor.detach().cpu().contiguous().numpy()
34
+ digest.update(str(value.dtype).encode())
35
+ digest.update(str(value.shape).encode())
36
+ digest.update(value.tobytes())
37
+ return digest.hexdigest()
38
+
39
+
40
+ def prediction_metrics(prediction, targets):
41
+ targets = np.asarray(targets, dtype=np.int64)
42
+ logits = np.asarray(prediction["answer_logits"], dtype=np.float64)
43
+ answer, stop = prediction["answer"], prediction["stop"]
44
+ if logits.ndim != 2 or logits.shape[0] != len(targets):
45
+ raise ValueError("Logits and targets must align")
46
+ if answer.shape != targets.shape or stop.shape != targets.shape:
47
+ raise ValueError("Generated answers and EOS must align with targets")
48
+ if not np.isfinite(logits).all():
49
+ raise ValueError("Nonfinite answer logits")
50
+ if len(targets) and (targets.min() < 0 or targets.max() >= logits.shape[1]):
51
+ raise ValueError("Target outside vocabulary")
52
+ maximum = logits.max(axis=1) if len(targets) else np.empty(0)
53
+ partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(axis=1))
54
+ target_logits = logits[np.arange(len(targets)), targets]
55
+ competitors = logits.copy()
56
+ competitors[np.arange(len(targets)), targets] = -np.inf
57
+ log_probability = target_logits - partition
58
+ return {
59
+ "answer_accuracy": (answer == targets).astype(np.float64),
60
+ "complete_accuracy": ((answer == targets) & (stop == 1)).astype(np.float64),
61
+ "eos_accuracy": (stop == 1).astype(np.float64),
62
+ "target_probability": np.exp(log_probability),
63
+ "target_log_probability": log_probability,
64
+ "target_margin": target_logits - competitors.max(axis=1),
65
+ }
66
+
67
+
68
+ def query_mean(values, recipient_indices, n_recipients):
69
+ """Missing recipients remain NaN; repeated donors never add query weight."""
70
+ values = np.asarray(values, dtype=np.float64)
71
+ indices = np.asarray(recipient_indices, dtype=np.int64)
72
+ if values.shape != indices.shape or not np.isfinite(values).all():
73
+ raise ValueError("Finite, aligned one-dimensional donor values are required")
74
+ if len(indices) and (indices.min() < 0 or indices.max() >= n_recipients):
75
+ raise ValueError("Recipient index outside query pool")
76
+ count = np.bincount(indices, minlength=n_recipients)
77
+ sums = np.bincount(indices, weights=values, minlength=n_recipients)
78
+ result = np.full(n_recipients, np.nan)
79
+ np.divide(sums, count, out=result, where=count > 0)
80
+ return result
81
+
82
+
83
+ def summarize(values, recipient_indices, selected, n_recipients):
84
+ selected = np.asarray(selected, dtype=bool)
85
+ if selected.shape != (n_recipients,):
86
+ raise ValueError("Selection must align with the complete recipient pool")
87
+ indices = np.asarray(recipient_indices, dtype=np.int64)
88
+ n = int(selected.sum())
89
+ metrics = {}
90
+ available = np.zeros(n_recipients, dtype=bool)
91
+ available[indices] = True
92
+ mask = selected & available
93
+ for name in METRICS:
94
+ balanced = query_mean(values[name], indices, n_recipients)
95
+ metrics[name] = float(balanced[mask].mean()) if mask.any() else None
96
+ return {
97
+ "n_recipients": int(mask.sum()),
98
+ "selected_recipients": n,
99
+ "total_recipients": n_recipients,
100
+ "coverage": float(mask.mean()) if n_recipients else None,
101
+ "n_donor_evaluations": int(selected[indices].sum()),
102
+ **metrics,
103
+ }
104
+
105
+
106
+ def _equal_predictions(left, right, label):
107
+ for name in ("answer", "stop", "answer_logits"):
108
+ if not np.array_equal(left[name], right[name]):
109
+ raise AssertionError(f"{label}: {name} differs")
110
+
111
+
112
+ def _fixed_batch_evaluate(model, inputs, device, physical_batch, **kwargs):
113
+ """Keep GPU matrix shapes equal to the full historical recipient batch.
114
+
115
+ Duplicate padding rows exist only to fill the physical batch and are
116
+ discarded before scoring or saving. No PAD row is treated as a donor.
117
+ """
118
+ if not len(inputs):
119
+ return evaluate_condition(model, inputs, device, 4, batch_size=physical_batch, **kwargs)
120
+ prefixes = kwargs.pop("donor_prefixes", None)
121
+ outputs = []
122
+ audits = []
123
+ for start in range(0, len(inputs), physical_batch):
124
+ actual = min(physical_batch, len(inputs) - start)
125
+ block = inputs[start : start + actual]
126
+ padded = np.concatenate([block, np.repeat(block[-1:], physical_batch - actual, axis=0)])
127
+ arguments = dict(kwargs)
128
+ if prefixes is not None:
129
+ prefix = prefixes[start : start + actual]
130
+ arguments["donor_prefixes"] = np.concatenate(
131
+ [prefix, np.repeat(prefix[-1:], physical_batch - actual, axis=0)]
132
+ )
133
+ prediction, audit = evaluate_condition(
134
+ model, padded, device, 4, batch_size=physical_batch, **arguments
135
+ )
136
+ outputs.append({field: value[:actual] for field, value in prediction.items()})
137
+ audits.append(audit)
138
+ return {field: np.concatenate([row[field] for row in outputs]) for field in outputs[0]}, {
139
+ "native_comparison_performed": all(row["native_comparison_performed"] for row in audits),
140
+ "native_max_logit_delta": max(row["native_max_logit_delta"] for row in audits),
141
+ "prefix_only_vs_full_all_layers_max_delta": max(
142
+ row["prefix_only_vs_full_all_layers_max_delta"] for row in audits
143
+ ),
144
+ "physical_batch_size": physical_batch,
145
+ "scored_evaluations": len(inputs),
146
+ "discarded_duplicate_padding": len(outputs) * physical_batch - len(inputs),
147
+ }
148
+
149
+
150
+ @torch.no_grad()
151
+ def evaluate_same_bridge(model, world, donors, *, device="cuda:0", batch_size=1024):
152
+ started = time.perf_counter()
153
+ model.eval()
154
+ before = state_digest(model)
155
+ if any(parameter.requires_grad for parameter in model.parameters()):
156
+ raise ValueError("All model parameters must be frozen")
157
+ rows = donors["original_rows"]
158
+ if not np.array_equal(rows, world["ood_composite"]) or rows.shape[1] != 4:
159
+ raise ValueError("Expected the unchanged complete pure-OOD two-hop pool")
160
+ n = len(rows)
161
+ arrays = {k: v.copy() for k, v in donors.items() if isinstance(v, np.ndarray)}
162
+ results, values, descriptions, engineering = {}, {}, {}, {}
163
+
164
+ def evaluate(name, inputs, indices, **kwargs):
165
+ prediction, audit = _fixed_batch_evaluate(
166
+ model, inputs, device, max(1, min(n, batch_size)), **kwargs
167
+ )
168
+ indices = np.asarray(indices, dtype=np.int64)
169
+ measured = prediction_metrics(prediction, inputs[:, -1])
170
+ for field, vector in {**prediction, **measured}.items():
171
+ arrays[name + "_" + field] = vector
172
+ arrays[name + "_recipient_indices"] = indices
173
+ results[name], values[name] = prediction, measured
174
+ descriptions[name] = {
175
+ "n_evaluations": len(inputs),
176
+ "patch_layer": kwargs.get("patch_layer"),
177
+ "component": kwargs.get("component"),
178
+ "identity": kwargs.get("identity", False),
179
+ "prefix_only": kwargs.get("donor_prefixes") is not None,
180
+ }
181
+ engineering[name] = audit
182
+ return prediction
183
+
184
+ all_indices = np.arange(n, dtype=np.int64)
185
+ baseline = evaluate("baseline", rows, all_indices, verify_trace=True)
186
+ for component in COMPONENTS:
187
+ self_result = evaluate(
188
+ "self_" + component,
189
+ rows,
190
+ all_indices,
191
+ patch_layer=0,
192
+ component=component,
193
+ identity=True,
194
+ )
195
+ prefix_result = evaluate(
196
+ "original_prefix_" + component,
197
+ rows,
198
+ all_indices,
199
+ patch_layer=0,
200
+ component=component,
201
+ donor_prefixes=rows[:, :2],
202
+ )
203
+ _equal_predictions(baseline, self_result, "self " + component)
204
+ _equal_predictions(baseline, prefix_result, "original prefix " + component)
205
+
206
+ atomic_prediction, atomic_audit = evaluate_condition(
207
+ model, world["atomic"], device, 4, batch_size=batch_size, verify_trace=True
208
+ )
209
+ arrays["atomic_rows"] = world["atomic"].copy()
210
+ for field, vector in atomic_prediction.items():
211
+ arrays["atomic_" + field] = vector
212
+ atomic_complete = (atomic_prediction["answer"] == world["atomic"][:, -1]) & (
213
+ atomic_prediction["stop"] == 1
214
+ )
215
+ arrays["atomic_complete_correct"] = atomic_complete
216
+ arrays["original_atomic_complete_correct"] = atomic_complete[donors["original_atomic_indices"]]
217
+ engineering["atomic_native"] = atomic_audit
218
+ atom_lookup = {tuple(map(int, r)): i for i, r in enumerate(world["atomic"])}
219
+ for family in ("id", "ood"):
220
+ indices = donors[family + "_recipient_indices"]
221
+ inputs = rows[indices]
222
+ donor_rows = donors[family + "_donor_rows"]
223
+ prefixes = donor_rows[:, :2]
224
+ counterfactual = inputs.copy()
225
+ counterfactual[:, 0] = donor_rows[:, 0]
226
+ atomic_indices = np.asarray(
227
+ [atom_lookup[tuple(map(int, r))] for r in donor_rows], dtype=np.int64
228
+ )
229
+ arrays[family + "_donor_atomic_indices"] = atomic_indices
230
+ arrays[family + "_donor_atomic_complete_correct"] = atomic_complete[atomic_indices]
231
+ matched = evaluate(family + "_baseline", inputs, indices)
232
+ _equal_predictions(
233
+ {k: v[indices] for k, v in baseline.items()}, matched, family + " batch match"
234
+ )
235
+ engineering[family + "_batch_shape_comparison"] = {
236
+ "answers_and_eos_identical": True,
237
+ "max_logit_delta": 0.0,
238
+ "bitwise_equal_full_logits": True,
239
+ "intervention_baseline_has_identical_batch_shape": True,
240
+ }
241
+ evaluate(family + "_counterfactual", counterfactual, indices)
242
+ self_result = evaluate(
243
+ family + "_self",
244
+ inputs,
245
+ indices,
246
+ patch_layer=0,
247
+ component="full",
248
+ identity=True,
249
+ )
250
+ _equal_predictions(matched, self_result, family + " self")
251
+ for component in COMPONENTS:
252
+ evaluate(
253
+ family + "_" + component,
254
+ inputs,
255
+ indices,
256
+ patch_layer=0,
257
+ component=component,
258
+ donor_prefixes=prefixes,
259
+ )
260
+ if len(executed_blocks(model)) == 1:
261
+ _equal_predictions(matched, results[family + "_" + component], "C1 inert patch")
262
+ _equal_predictions(
263
+ results[family + "_both"], results[family + "_full"], family + " both/full"
264
+ )
265
+
266
+ common = donors["common_valid"]
267
+ groups = {
268
+ "all": np.ones(n, dtype=bool),
269
+ "paired": common,
270
+ "id_only": (donors["id_candidate_count"] > 0) & (donors["ood_candidate_count"] == 0),
271
+ "ood_only": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] > 0),
272
+ "neither": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] == 0),
273
+ "paired_original_atomics_correct": common
274
+ & arrays["original_atomic_complete_correct"].all(axis=1),
275
+ "paired_baseline_failed": common & (values["baseline"]["complete_accuracy"] == 0),
276
+ "paired_baseline_correct": common & (values["baseline"]["complete_accuracy"] == 1),
277
+ }
278
+ # Conditional diagnostics are reported alongside the unfiltered paired pool.
279
+ pid, pod = donors["pair_id_indices"], donors["pair_ood_indices"]
280
+ pair_indices = donors["pair_recipient_indices"]
281
+ known_pair = arrays["original_atomic_complete_correct"][pair_indices].all(axis=1)
282
+ known_pair &= arrays["id_donor_atomic_complete_correct"][pid]
283
+ known_pair &= arrays["ood_donor_atomic_complete_correct"][pod]
284
+ cf_pair = values["id_counterfactual"]["complete_accuracy"][pid].astype(bool)
285
+ cf_pair &= values["ood_counterfactual"]["complete_accuracy"][pod].astype(bool)
286
+ arrays["pair_all_atomics_correct"] = known_pair
287
+ arrays["pair_both_counterfactual_correct"] = cf_pair
288
+ # A query is included in the following conditional subset only if every
289
+ # registered donor pair satisfies the prerequisite, avoiding donor picking.
290
+ for name, flag in (
291
+ ("all_atomics_correct", known_pair),
292
+ ("both_counterfactual_correct", cf_pair),
293
+ ):
294
+ average = query_mean(flag.astype(float), pair_indices, n)
295
+ groups["paired_" + name] = common & (average == 1)
296
+ for name, mask in groups.items():
297
+ arrays["subset_" + name] = mask
298
+
299
+ scores = {}
300
+ for group, selected in groups.items():
301
+ scores[group] = {
302
+ condition: summarize(measured, arrays[condition + "_recipient_indices"], selected, n)
303
+ for condition, measured in values.items()
304
+ }
305
+ contrasts = {}
306
+ for component in COMPONENTS:
307
+ id_values, ood_values = values["id_" + component], values["ood_" + component]
308
+ difference = {
309
+ metric: id_values[metric][pid] - ood_values[metric][pod] for metric in METRICS
310
+ }
311
+ adjusted = {
312
+ metric: (id_values[metric][pid] - values["id_baseline"][metric][pid])
313
+ - (ood_values[metric][pod] - values["ood_baseline"][metric][pod])
314
+ for metric in METRICS
315
+ }
316
+ for group, mask in groups.items():
317
+ contrasts[group + ":" + component] = {
318
+ "id_minus_ood": summarize(difference, pair_indices, mask, n),
319
+ "baseline_adjusted_id_minus_ood": summarize(adjusted, pair_indices, mask, n),
320
+ }
321
+ after = state_digest(model)
322
+ if before != after:
323
+ raise AssertionError("Interventions changed model parameters or buffers")
324
+ return arrays, {
325
+ "seconds": time.perf_counter() - started,
326
+ "n_original_queries": n,
327
+ "n_common_queries": int(common.sum()),
328
+ "n_pairs": len(pair_indices),
329
+ "conditions": descriptions,
330
+ "scores": scores,
331
+ "contrasts": contrasts,
332
+ "engineering": {
333
+ "native_and_prefix_checks": engineering,
334
+ "all_self_and_original_prefix_conditions_equal_baseline": True,
335
+ "both_equals_full_first_execution_layer": True,
336
+ "c1_last_block_inert": len(executed_blocks(model)) == 1,
337
+ "parameters_unchanged": True,
338
+ "model_state_sha256_before": before,
339
+ "model_state_sha256_after": after,
340
+ "mlp_recomputed_after_mixing": False,
341
+ "donor_nonpadding_tokens": 2,
342
+ "patch_layer": 0,
343
+ "patch_position": 1,
344
+ "eos_uses_generated_answer": True,
345
+ "training_updates": 0,
346
+ "physical_condition_batch_size": max(1, min(n, batch_size)),
347
+ "duplicate_padding_never_scored_or_saved": True,
348
+ },
349
+ "statistical_unit": (
350
+ "mean over all donors within recipient; initialization within world; equal worlds"
351
+ ),
352
+ "selection": "graph and registered training exposures only; scores do not select donors",
353
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired continuation: terminal versus distributed answer supervision.
2
+
3
+ Historical model/trainer files remain unchanged. All heads branch off the same
4
+ trajectory; their LayerNorm outputs never replace the recurrent residual state.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import torch
17
+ from torch.nn import functional as F
18
+
19
+ from .bios_model import ModelConfig
20
+ from .grok_depth import GraphStep, make_optimizer, utc, write_json
21
+ from .grok_loop_data import StratifiedStream
22
+ from .grok_loop_model import LoopGPT, flops
23
+ from .grok_multihop import pack_rows
24
+
25
+
26
+ def digest(path):
27
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
28
+
29
+
30
+ def tensor_digest(tensors):
31
+ h = hashlib.sha256()
32
+ for key, value in sorted(tensors.items()):
33
+ h.update(key.encode())
34
+ h.update(value.detach().cpu().contiguous().numpy().tobytes())
35
+ return h.hexdigest()
36
+
37
+
38
+ class SupervisionGPT(LoopGPT):
39
+ def states(self, tokens, repeats):
40
+ """Yield full group-boundary states with exactly the native dropout order."""
41
+ p = self.dropout if self.training else 0.0
42
+ x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
43
+ x = F.dropout(x, p=p, training=self.training)
44
+ for _ in range(repeats):
45
+ for block in self.blocks:
46
+ z = block.ln1(x)
47
+ batch, length, width = z.shape
48
+ a = block.attention
49
+ q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
50
+ y = F.scaled_dot_product_attention(
51
+ q.transpose(1, 2),
52
+ k.transpose(1, 2),
53
+ v.transpose(1, 2),
54
+ is_causal=True,
55
+ dropout_p=p,
56
+ )
57
+ y = a.proj(y.transpose(1, 2).reshape(batch, length, width))
58
+ x = x + F.dropout(y, p=p, training=self.training)
59
+ x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training)
60
+ yield x
61
+
62
+ def readout(self, x, positions=None):
63
+ x = self.ln_final(x)
64
+ if positions is not None:
65
+ x = x[torch.arange(len(x), device=x.device)[:, None], positions]
66
+ return F.linear(x, self.token.weight)
67
+
68
+ def at_loops(self, tokens, positions, loops=(2, 3, 4)):
69
+ if not loops or tuple(sorted(set(loops))) != tuple(loops) or loops[0] < 1:
70
+ raise ValueError("Loop endpoints must be positive, unique, sorted")
71
+ return tuple(
72
+ self.readout(x, positions)
73
+ for r, x in enumerate(self.states(tokens, max(loops)), 1)
74
+ if r in loops
75
+ )
76
+
77
+
78
+ def answer_losses(model, x, positions, labels):
79
+ return torch.stack(
80
+ [F.cross_entropy(z.flatten(0, 1), labels.flatten()) for z in model.at_loops(x, positions)]
81
+ )
82
+
83
+
84
+ class SupervisionStep(GraphStep):
85
+ """Both arms execute all three CE/backward branches, including zero weights."""
86
+
87
+ def __init__(self, model, optimizer, table, batch_size, arm):
88
+ if arm not in ("single", "multi"):
89
+ raise ValueError(arm)
90
+ weights = [0.0, 0.0, 1.0] if arm == "single" else [1 / 3] * 3
91
+ self.weights = torch.tensor(weights, device=table[0].device)
92
+ super().__init__(model, optimizer, table, batch_size)
93
+
94
+ def eager(self):
95
+ self.optimizer.zero_grad(set_to_none=False)
96
+ x, pos, labels = (t[self.index] for t in self.table)
97
+ self.components = answer_losses(self.model, x, pos, labels)
98
+ loss = (self.components * self.weights).sum()
99
+ loss.backward()
100
+ norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
101
+ self.optimizer.step()
102
+ return loss, norm
103
+
104
+
105
+ def from_state(state, device):
106
+ spec = state["spec"]
107
+ cfg = ModelConfig(
108
+ vocab_size=2 + spec["entities"] + spec["relations"],
109
+ width=spec["width"],
110
+ layers=spec["layers"],
111
+ heads=spec["heads"],
112
+ context=8,
113
+ )
114
+ model = SupervisionGPT(
115
+ cfg,
116
+ repeats=spec["repeats"],
117
+ dropout=spec["dropout"],
118
+ initialization=spec["init_scheme"],
119
+ ).to(device)
120
+ model.load_state_dict(state["model"])
121
+ return model
122
+
123
+
124
+ def score_predictions(pred):
125
+ correct = pred["answer"] == pred["target"]
126
+ return {
127
+ "n": len(correct),
128
+ "accuracy": float((correct & (pred["stop"] == 1)).mean()),
129
+ "answer_accuracy": float(correct.mean()),
130
+ "eos_accuracy": float((pred["stop"] == 1).mean()),
131
+ "nll": float(pred["nll"].mean()),
132
+ "answer_nll": float(pred["nll"][:, 0].mean()),
133
+ "answer_probability": float(np.exp(-pred["nll"][:, 0].astype(float)).mean()),
134
+ "margin": float(pred["margin"].mean()),
135
+ }
136
+
137
+
138
+ @torch.no_grad()
139
+ def evaluate(model, rows, device, repeats, batch_size=1024):
140
+ was_training = model.training
141
+ model.eval()
142
+ packed = pack_rows(rows, 4)
143
+ parts = []
144
+ for start in range(0, len(rows), batch_size):
145
+ x, pos, labels = (
146
+ torch.as_tensor(a[start : start + batch_size], device=device) for a in packed
147
+ )
148
+ x = x.clone()
149
+ z = model(x, pos, repeats=repeats)
150
+ nll = F.cross_entropy(z.flatten(0, 1), labels.flatten(), reduction="none").view(-1, 2)
151
+ answer = z[:, 0].argmax(-1)
152
+ x[torch.arange(len(x), device=device), pos[:, 1]] = answer
153
+ eos = model(x, pos, repeats=repeats)[:, 1]
154
+ target_score = z[:, 0].gather(1, labels[:, :1]).squeeze(1)
155
+ alternatives = z[:, 0].clone()
156
+ alternatives.scatter_(1, labels[:, :1], -torch.inf)
157
+ parts.append(
158
+ {
159
+ "answer": answer.cpu().numpy(),
160
+ "stop": eos.argmax(-1).cpu().numpy(),
161
+ "target": labels[:, 0].cpu().numpy(),
162
+ "nll": nll.cpu().numpy(),
163
+ "margin": (target_score - alternatives.max(-1).values).cpu().numpy(),
164
+ "logits": z.cpu().numpy(),
165
+ "generated_eos_logits": eos.cpu().numpy(),
166
+ }
167
+ )
168
+ model.train(was_training)
169
+ pred = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]}
170
+ return score_predictions(pred), pred
171
+
172
+
173
+ def load_world(source):
174
+ with np.load(Path(source) / "world.npz", allow_pickle=False) as z:
175
+ world = {k: z[k].copy() for k in z.files}
176
+ world["metadata"] = json.loads((Path(source) / "world-metadata.json").read_text())
177
+ return world
178
+
179
+
180
+ def restore_rng(state, device):
181
+ torch.set_rng_state(state["cpu_rng"].cpu())
182
+ torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
183
+
184
+
185
+ def run(spec, out, device, resume=False):
186
+ out, device = Path(out), torch.device(device)
187
+ source = Path(spec["source"])
188
+ origin = torch.load(source / "latest.pt", map_location=device, weights_only=False)
189
+ if origin["step"] != 128000 or origin["spec"]["hops"] != 2:
190
+ raise ValueError("Expected completed historical two-hop checkpoint")
191
+ world = load_world(source)
192
+ current = (
193
+ torch.load(out / "latest.pt", map_location=device, weights_only=False) if resume else origin
194
+ )
195
+ if resume and current["continuation"] != spec:
196
+ raise ValueError("Resume contract changed")
197
+ model = from_state(current, device)
198
+ lr = torch.tensor(spec["lr"], device=device)
199
+ opt = make_optimizer(model, lr, origin["spec"]["weight_decay"])
200
+ opt.load_state_dict(current["optimizer"])
201
+ lr = opt.param_groups[0]["lr"]
202
+ for group in opt.param_groups:
203
+ group["lr"] = lr
204
+ lr.fill_(spec["lr"])
205
+ packed = [pack_rows(world[name], 4) for name in ("atomic", "train_composite")]
206
+ table = tuple(
207
+ torch.as_tensor(np.concatenate(a), device=device) for a in zip(*packed, strict=True)
208
+ )
209
+ stream = StratifiedStream(
210
+ len(world["atomic"]),
211
+ len(world["train_composite"]),
212
+ 256,
213
+ 32,
214
+ origin["spec"]["stream_seed"],
215
+ )
216
+ stream.load_state_dict(current["stream"])
217
+ restore_rng(current, device)
218
+ step = current["step"] if resume else 0
219
+ training_seconds = current.get("continuation_training_seconds", 0.0) if resume else 0.0
220
+ records = json.loads((out / "learning.json").read_text()) if resume else []
221
+ records = [r for r in records if r["step"] <= step]
222
+ before_capture = tensor_digest(model.state_dict())
223
+ optimizer_before = {
224
+ p: {k: v.clone() for k, v in s.items() if torch.is_tensor(v)} for p, s in opt.state.items()
225
+ }
226
+ model.train()
227
+ graph = SupervisionStep(model, opt, table, 256, spec["arm"])
228
+ capture_ok = before_capture == tensor_digest(model.state_dict()) and all(
229
+ torch.equal(v, opt.state[p][k]) for p, s in optimizer_before.items() for k, v in s.items()
230
+ )
231
+ if not capture_ok:
232
+ raise ValueError("CUDA capture altered source model/optimizer")
233
+ del optimizer_before
234
+ flop_step = flops(model.config, 4, 256, 4, output_positions=6)
235
+ sampling_hash = hashlib.sha256()
236
+ # Persist cumulative per-row exposure as well as stream state for paired audit.
237
+ exposure = (
238
+ current["continuation_exposure"].cpu().numpy()
239
+ if resume
240
+ else np.zeros(len(table[0]), dtype=np.int64)
241
+ )
242
+
243
+ def measure(at, components=None):
244
+ rng = {"cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device)}
245
+ row = {
246
+ "step": at,
247
+ "utc": utc(),
248
+ "training_seconds": training_seconds,
249
+ "estimated_training_matmul_flops": at * flop_step,
250
+ "logical_examples": at * 256,
251
+ "atomic_presentations": at * 32,
252
+ "composite_presentations": at * 224,
253
+ "weighted_target_tokens": at * 256 * 2,
254
+ "executed_loss_target_tokens": at * 256 * 2 * 3,
255
+ "last_batch_losses_2_3_4": components,
256
+ "evaluations": {},
257
+ }
258
+ repeats = spec["endpoint_repeats"] if at in (0, spec["steps"]) else [2, 3, 4, 8]
259
+ preds = {}
260
+ for name in ("atomic", "test_full_composite", "ood_composite", "train_composite"):
261
+ counts = [2, 3, 4] if name == "train_composite" else repeats
262
+ for r in counts:
263
+ metric, pred = evaluate(model, world[name], device, r)
264
+ key = f"{name}_r{r}"
265
+ row["evaluations"][key] = metric
266
+ preds.update({key + "_" + k: v for k, v in pred.items()})
267
+ if name == "atomic":
268
+ for subset in ("id_atomic", "ood_atomic"):
269
+ ids = {tuple(x) for x in world[subset]}
270
+ mask = np.array([tuple(x) in ids for x in world["atomic"]])
271
+ row["evaluations"][f"{subset}_r{r}"] = score_predictions(
272
+ {k: v[mask] for k, v in pred.items()}
273
+ )
274
+ records.append(row)
275
+ write_json(out / "learning.json", records)
276
+ np.savez_compressed(out / f"predictions-{at:07d}.npz", **preds)
277
+ restore_rng(rng, device)
278
+ state = {
279
+ "spec": origin["spec"],
280
+ "continuation": spec,
281
+ "step": at,
282
+ "source_training_step": origin["step"],
283
+ "model": model.state_dict(),
284
+ "optimizer": opt.state_dict(),
285
+ "stream": stream.state_dict(),
286
+ "cpu_rng": rng["cpu_rng"],
287
+ "cuda_rng": rng["cuda_rng"],
288
+ "continuation_exposure": torch.as_tensor(exposure),
289
+ "continuation_training_seconds": training_seconds,
290
+ }
291
+ torch.save(state, out / "latest.tmp.pt")
292
+ (out / "latest.tmp.pt").replace(out / "latest.pt")
293
+ torch.save(
294
+ {"spec": origin["spec"], "step": at, "model": model.state_dict()},
295
+ out / f"weights-{at:07d}.pt",
296
+ )
297
+ ev = row["evaluations"]
298
+ status = {
299
+ "state": "complete" if at == spec["steps"] else "running",
300
+ "step": at,
301
+ "arm": spec["arm"],
302
+ "ood_r4": ev["ood_composite_r4"]["accuracy"],
303
+ "ood_r8": ev["ood_composite_r8"]["accuracy"],
304
+ "atomic_r4": ev["atomic_r4"]["accuracy"],
305
+ "id_r4": ev["test_full_composite_r4"]["accuracy"],
306
+ "utc": utc(),
307
+ }
308
+ write_json(out / "status.json", status)
309
+ print(json.dumps(status), flush=True)
310
+ return row
311
+
312
+ if not resume:
313
+ measure(0)
314
+ for end in [n for n in spec["nodes"] if n > step]:
315
+ model.train()
316
+ torch.cuda.synchronize()
317
+ start = time.perf_counter()
318
+ while step < end:
319
+ n = min(256, end - step)
320
+ ix = np.stack([stream.take() for _ in range(n)])
321
+ exposure += np.bincount(ix.ravel(), minlength=len(exposure))
322
+ sampling_hash.update(ix.tobytes())
323
+ gpu_ix = torch.as_tensor(ix, device=device)
324
+ for j in range(n):
325
+ graph(gpu_ix[j])
326
+ step += n
327
+ torch.cuda.synchronize()
328
+ training_seconds += time.perf_counter() - start
329
+ values = graph.components.detach().cpu().tolist()
330
+ if not all(math.isfinite(v) for v in values):
331
+ raise FloatingPointError(f"Nonfinite component losses at {step}")
332
+ measure(step, values)
333
+ if not records or records[-1]["step"] != spec["steps"]:
334
+ raise ValueError("Budget not reached")
335
+ write_json(
336
+ out / "complete.json",
337
+ {
338
+ "spec": spec,
339
+ "completed_utc": utc(),
340
+ "capture_restore_passed": capture_ok,
341
+ "training_seconds": training_seconds,
342
+ "endpoint": records[-1],
343
+ "initial_model_sha256": tensor_digest(origin["model"]),
344
+ "final_model_sha256": tensor_digest(model.state_dict()),
345
+ "exposure_sha256": hashlib.sha256(exposure.tobytes()).hexdigest(),
346
+ "sampling_segment_sha256": sampling_hash.hexdigest(),
347
+ "segment_start": current["step"] if resume else 0,
348
+ },
349
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_train.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from .bios_model import ModelConfig
14
+ from .grok_depth import GraphStep, make_optimizer, utc, write_json
15
+ from .grok_loop_data import StratifiedStream
16
+ from .grok_loop_model import LoopGPT, flops
17
+ from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows
18
+
19
+
20
+ def run(spec, world, out, device="cuda:0", resume=False):
21
+ out = Path(out)
22
+ out.mkdir(parents=True, exist_ok=True)
23
+ torch.set_num_threads(1)
24
+ torch.set_num_interop_threads(1)
25
+ torch.backends.cuda.matmul.allow_tf32 = True
26
+ torch.backends.cudnn.allow_tf32 = True
27
+ torch.manual_seed(spec["initialization"])
28
+ torch.cuda.manual_seed_all(spec["initialization"])
29
+ device = torch.device(device)
30
+ torch.cuda.set_device(device)
31
+ padded_length = spec["hops"] + 2
32
+ cfg = ModelConfig(
33
+ vocab_size=2 + spec["entities"] + spec["relations"],
34
+ width=spec["width"],
35
+ layers=spec["layers"],
36
+ heads=spec["heads"],
37
+ context=8,
38
+ )
39
+ model = LoopGPT(
40
+ cfg,
41
+ repeats=spec["repeats"],
42
+ dropout=spec["dropout"],
43
+ initialization=spec["init_scheme"],
44
+ ).to(device)
45
+ lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device)
46
+ opt = make_optimizer(model, lr, spec["weight_decay"])
47
+ atoms = pack_rows(world["atomic"], padded_length)
48
+ comps = pack_rows(world["train_composite"], padded_length)
49
+ table = tuple(
50
+ torch.as_tensor(np.concatenate([a, c]), device=device)
51
+ for a, c in zip(atoms, comps, strict=True)
52
+ )
53
+ stream = StratifiedStream(
54
+ len(world["atomic"]),
55
+ len(world["train_composite"]),
56
+ spec["batch_size"],
57
+ spec["n_atomic_per_batch"],
58
+ spec["stream_seed"],
59
+ )
60
+ counts = {"atomic": 0, "composite": 0}
61
+ elapsed_training, elapsed_eval = 0.0, 0.0
62
+ start_step = 0
63
+ checkpoint = out / "latest.pt"
64
+ if resume:
65
+ state = torch.load(checkpoint, map_location=device, weights_only=False)
66
+ if state["spec"] != spec:
67
+ raise ValueError("Resume spec differs from saved state")
68
+ model.load_state_dict(state["model"])
69
+ opt.load_state_dict(state["optimizer"])
70
+ lr = opt.param_groups[0]["lr"]
71
+ for group in opt.param_groups:
72
+ group["lr"] = lr
73
+ stream.load_state_dict(state["stream"])
74
+ counts = state["counts"]
75
+ elapsed_training = state["elapsed_training"]
76
+ elapsed_eval = state["elapsed_eval"]
77
+ start_step = state["step"]
78
+ torch.set_rng_state(state["cpu_rng"].cpu())
79
+ torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
80
+ started = time.perf_counter()
81
+ graph = GraphStep(model, opt, table, spec["batch_size"])
82
+ capture_seconds = time.perf_counter() - started
83
+ names = (
84
+ "atomic",
85
+ "id_atomic",
86
+ "ood_atomic",
87
+ "train_composite",
88
+ "test_composite",
89
+ "ood_composite",
90
+ )
91
+ nparams = sum(p.numel() for p in model.parameters())
92
+ flop_step = flops(
93
+ cfg, spec["repeats"], spec["batch_size"], sequence=padded_length, output_positions=2
94
+ )
95
+ rows_log = []
96
+ if (out / "learning.json").exists():
97
+ rows_log = json.loads((out / "learning.json").read_text())
98
+ if resume:
99
+ rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values())
100
+ rows_log.sort(key=lambda row: row["step"])
101
+
102
+ def measure(step, last_loss=None):
103
+ nonlocal elapsed_eval
104
+ torch.cuda.synchronize()
105
+ t0 = time.perf_counter()
106
+ row = {
107
+ "step": step,
108
+ "utc": utc(),
109
+ "hops": spec["hops"],
110
+ "parameters": nparams,
111
+ "unique_layers": spec["layers"],
112
+ "repeats": spec["repeats"],
113
+ "effective_depth": spec["layers"] * spec["repeats"],
114
+ "training_seconds": elapsed_training,
115
+ "capture_seconds": capture_seconds,
116
+ "examples": step * spec["batch_size"],
117
+ "counts": counts.copy(),
118
+ "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length,
119
+ "supervised_tokens": step * spec["batch_size"] * 2,
120
+ "estimated_training_flops": step * flop_step,
121
+ "last_batch_loss": last_loss,
122
+ }
123
+ predictions = {}
124
+ selected_names = names + (("test_full_composite",) if step == spec["steps"] else ())
125
+ for name in selected_names:
126
+ row[name], pred = evaluate_rows(model, world[name], device, padded_length)
127
+ predictions.update({name + "_" + key: value for key, value in pred.items()})
128
+ row["autonomous_calls"], calls_pred = autonomous_calls(
129
+ model, world["test_composite"], world, device, padded_length
130
+ )
131
+ predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()})
132
+ torch.cuda.synchronize()
133
+ elapsed_eval += time.perf_counter() - t0
134
+ row["evaluation_seconds"] = elapsed_eval
135
+ rows_log.append(row)
136
+ write_json(out / "learning.json", rows_log)
137
+ np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions)
138
+ state = {
139
+ "step": step,
140
+ "spec": spec,
141
+ "model": model.state_dict(),
142
+ "optimizer": opt.state_dict(),
143
+ "stream": stream.state_dict(),
144
+ "counts": counts,
145
+ "elapsed_training": elapsed_training,
146
+ "elapsed_eval": elapsed_eval,
147
+ "cpu_rng": torch.get_rng_state(),
148
+ "cuda_rng": torch.cuda.get_rng_state(device),
149
+ }
150
+ torch.save(state, out / "latest.tmp.pt")
151
+ (out / "latest.tmp.pt").replace(checkpoint)
152
+ if step in spec["weight_nodes"]:
153
+ torch.save(
154
+ {"spec": spec, "step": step, "model": model.state_dict()},
155
+ out / f"weights-{step:07d}.pt",
156
+ )
157
+ status = {
158
+ "state": "complete" if step == spec["steps"] else "running",
159
+ "step": step,
160
+ "budget": spec["steps"],
161
+ "updated_utc": utc(),
162
+ "hops": spec["hops"],
163
+ "layers": spec["layers"],
164
+ "atomic": row["atomic"]["accuracy"],
165
+ "train": row["train_composite"]["accuracy"],
166
+ "test_probe": row["test_composite"]["accuracy"],
167
+ }
168
+ write_json(out / "status.json", status)
169
+ print(json.dumps(status), flush=True)
170
+ return row
171
+
172
+ if not resume:
173
+ measure(0)
174
+ if start_step < spec["steps"]:
175
+ for end in (s for s in spec["nodes"] if s > start_step):
176
+ last_loss = None
177
+ torch.cuda.synchronize()
178
+ t0 = time.perf_counter()
179
+ step = start_step
180
+ while step < end:
181
+ n = min(512, end - step)
182
+ ix = np.stack([stream.take() for _ in range(n)])
183
+ atom_count = int((ix < len(world["atomic"])).sum())
184
+ counts["atomic"] += atom_count
185
+ counts["composite"] += ix.size - atom_count
186
+ gpu_ix = torch.as_tensor(ix, device=device)
187
+ for j in range(n):
188
+ lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"]))
189
+ last_loss = graph(gpu_ix[j])
190
+ step += n
191
+ torch.cuda.synchronize()
192
+ elapsed_training += time.perf_counter() - t0
193
+ loss_value = float(last_loss.detach())
194
+ if not math.isfinite(loss_value):
195
+ raise FloatingPointError(f"Nonfinite loss at step {end}")
196
+ measure(end, loss_value)
197
+ start_step = end
198
+ if not rows_log or rows_log[-1]["step"] != spec["steps"]:
199
+ raise ValueError("Evaluation nodes did not reach the fixed budget")
200
+ write_json(
201
+ out / "complete.json",
202
+ {
203
+ "finished_utc": utc(),
204
+ "spec": spec,
205
+ "parameters": nparams,
206
+ "unique_layers": spec["layers"],
207
+ "repeats": spec["repeats"],
208
+ "effective_depth": spec["layers"] * spec["repeats"],
209
+ "training_seconds": elapsed_training,
210
+ "evaluation_seconds": elapsed_eval,
211
+ "endpoint": rows_log[-1],
212
+ },
213
+ )
214
+ return rows_log[-1]
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Longer-path trainer reusing the historical GPT, optimizer and graph step.
2
+
3
+ The only task changes are longer input rows and the separately audited split.
4
+ Training uses the same uniform combined-set epochs and tail-plus-EOS loss.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import torch
16
+ from torch.nn import functional as F
17
+
18
+ from .bios_model import ModelConfig, matmul_flops
19
+ from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json
20
+ from .grok_multihop_data import path_details
21
+
22
+
23
+ def pack_rows(rows, padded_length):
24
+ rows = np.asarray(rows, dtype=np.int64)
25
+ if rows.ndim != 2 or rows.shape[1] > padded_length or rows.shape[1] < 3:
26
+ raise ValueError("Rows must fit the fixed padded length and include an answer")
27
+ x = np.zeros((len(rows), padded_length), dtype=np.int64)
28
+ x[:, : rows.shape[1]] = rows
29
+ positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1))
30
+ labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)]
31
+ return x, positions, labels
32
+
33
+
34
+ @torch.no_grad()
35
+ def evaluate_rows(model, rows, device, padded_length, batch_size=1024):
36
+ was_training = model.training
37
+ model.eval()
38
+ packed = pack_rows(rows, padded_length)
39
+ answers, stops, losses = [], [], []
40
+ for start in range(0, len(rows), batch_size):
41
+ x, positions, labels = (
42
+ torch.as_tensor(a[start : start + batch_size], device=device) for a in packed
43
+ )
44
+ # as_tensor shares CPU memory when device=cpu; all writes occur in a copy.
45
+ x = x.clone()
46
+ logits = model(x, positions)
47
+ losses.append(
48
+ F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none")
49
+ .view(-1, 2)
50
+ .cpu()
51
+ .numpy()
52
+ )
53
+ answer = logits[:, 0].argmax(-1)
54
+ x[torch.arange(len(x), device=device), positions[:, 1]] = answer
55
+ stop = model(x, positions)[:, 1].argmax(-1)
56
+ answers.append(answer.cpu().numpy())
57
+ stops.append(stop.cpu().numpy())
58
+ model.train(was_training)
59
+ if not len(rows):
60
+ return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {}
61
+ answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses)
62
+ correct = answer == rows[:, -1]
63
+ return {
64
+ "n": len(rows),
65
+ "answer_accuracy": float(correct.mean()),
66
+ "accuracy": float((correct & (stop == 1)).mean()),
67
+ "nll": float(nll.mean()),
68
+ }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]}
69
+
70
+
71
+ @torch.no_grad()
72
+ def autonomous_calls(model, rows, world, device, padded_length):
73
+ """Supply relation decomposition, but carry the model's own intermediate answers."""
74
+ if not len(rows):
75
+ return {"n": 0, "answer_accuracy": None, "accuracy": None}, {}
76
+ meta = world["metadata"]
77
+ nodes, _ = path_details(rows, world["atomic"], meta["entities"], meta["relations"])
78
+ current = rows[:, 0].copy()
79
+ all_eos = np.ones(len(rows), dtype=bool)
80
+ all_correct = np.ones(len(rows), dtype=bool)
81
+ predictions, hop_accuracy = {}, []
82
+ for j in range(meta["hops"]):
83
+ # Gold target only scores the answer; causality prevents answer-label access.
84
+ queries = np.c_[current, rows[:, j + 1], nodes[:, j + 1]]
85
+ metrics, pred = evaluate_rows(model, queries, device, padded_length)
86
+ current = pred["answer"]
87
+ all_eos &= pred["stop"] == 1
88
+ all_correct &= current == nodes[:, j + 1]
89
+ hop_accuracy.append(metrics["accuracy"])
90
+ predictions[f"hop{j + 1}_answer"] = current
91
+ predictions[f"hop{j + 1}_stop"] = pred["stop"]
92
+ return {
93
+ "n": len(rows),
94
+ "calls": meta["hops"],
95
+ "answer_accuracy": float((current == rows[:, -1]).mean()),
96
+ "accuracy": float(((current == rows[:, -1]) & all_eos).mean()),
97
+ "all_intermediate_answers_and_eos_correct": float((all_correct & all_eos).mean()),
98
+ "hop_accuracy": hop_accuracy,
99
+ "extra_information": "given relation decomposition, own generated bridge entities",
100
+ }, predictions
101
+
102
+
103
+ def run(spec, world, out, device="cuda:0", resume=False):
104
+ out = Path(out)
105
+ out.mkdir(parents=True, exist_ok=True)
106
+ torch.set_num_threads(1)
107
+ torch.set_num_interop_threads(1)
108
+ torch.backends.cuda.matmul.allow_tf32 = True
109
+ torch.backends.cudnn.allow_tf32 = True
110
+ torch.manual_seed(spec["initialization"])
111
+ torch.cuda.manual_seed_all(spec["initialization"])
112
+ device = torch.device(device)
113
+ torch.cuda.set_device(device)
114
+ padded_length = spec["hops"] + 2
115
+ cfg = ModelConfig(
116
+ vocab_size=2 + spec["entities"] + spec["relations"],
117
+ width=spec["width"],
118
+ layers=spec["layers"],
119
+ heads=spec["heads"],
120
+ context=8,
121
+ )
122
+ model = SmallGPT(cfg, spec["dropout"]).to(device)
123
+ lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device)
124
+ opt = make_optimizer(model, lr, spec["weight_decay"])
125
+ atoms = pack_rows(world["atomic"], padded_length)
126
+ comps = pack_rows(world["train_composite"], padded_length)
127
+ table = tuple(
128
+ torch.as_tensor(np.concatenate([a, c]), device=device)
129
+ for a, c in zip(atoms, comps, strict=True)
130
+ )
131
+ stream = EpochStream(len(table[0]), spec["stream_seed"])
132
+ counts = {"atomic": 0, "composite": 0}
133
+ elapsed_training, elapsed_eval = 0.0, 0.0
134
+ start_step = 0
135
+ checkpoint = out / "latest.pt"
136
+ if resume:
137
+ state = torch.load(checkpoint, map_location=device, weights_only=False)
138
+ if state["spec"] != spec:
139
+ raise ValueError("Resume spec differs from saved state")
140
+ model.load_state_dict(state["model"])
141
+ opt.load_state_dict(state["optimizer"])
142
+ lr = opt.param_groups[0]["lr"]
143
+ for group in opt.param_groups:
144
+ group["lr"] = lr
145
+ stream.load_state_dict(state["stream"])
146
+ counts = state["counts"]
147
+ elapsed_training = state["elapsed_training"]
148
+ elapsed_eval = state["elapsed_eval"]
149
+ start_step = state["step"]
150
+ torch.set_rng_state(state["cpu_rng"].cpu())
151
+ torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
152
+ started = time.perf_counter()
153
+ graph = GraphStep(model, opt, table, spec["batch_size"])
154
+ capture_seconds = time.perf_counter() - started
155
+ names = (
156
+ "atomic",
157
+ "id_atomic",
158
+ "ood_atomic",
159
+ "train_composite",
160
+ "test_composite",
161
+ "ood_composite",
162
+ )
163
+ nparams = sum(p.numel() for p in model.parameters())
164
+ flop_step = matmul_flops(cfg, spec["batch_size"], sequence=padded_length, output_positions=2)
165
+ rows_log = []
166
+ if (out / "learning.json").exists():
167
+ rows_log = json.loads((out / "learning.json").read_text())
168
+ if resume:
169
+ rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values())
170
+ rows_log.sort(key=lambda row: row["step"])
171
+
172
+ def measure(step, last_loss=None):
173
+ nonlocal elapsed_eval
174
+ torch.cuda.synchronize()
175
+ t0 = time.perf_counter()
176
+ row = {
177
+ "step": step,
178
+ "utc": utc(),
179
+ "hops": spec["hops"],
180
+ "parameters": nparams,
181
+ "training_seconds": elapsed_training,
182
+ "capture_seconds": capture_seconds,
183
+ "examples": step * spec["batch_size"],
184
+ "counts": counts.copy(),
185
+ "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length,
186
+ "supervised_tokens": step * spec["batch_size"] * 2,
187
+ "estimated_training_flops": step * flop_step,
188
+ "last_batch_loss": last_loss,
189
+ }
190
+ predictions = {}
191
+ selected_names = names + (("test_full_composite",) if step == spec["steps"] else ())
192
+ for name in selected_names:
193
+ row[name], pred = evaluate_rows(model, world[name], device, padded_length)
194
+ predictions.update({name + "_" + key: value for key, value in pred.items()})
195
+ row["autonomous_calls"], calls_pred = autonomous_calls(
196
+ model, world["test_composite"], world, device, padded_length
197
+ )
198
+ predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()})
199
+ torch.cuda.synchronize()
200
+ elapsed_eval += time.perf_counter() - t0
201
+ row["evaluation_seconds"] = elapsed_eval
202
+ rows_log.append(row)
203
+ write_json(out / "learning.json", rows_log)
204
+ np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions)
205
+ state = {
206
+ "step": step,
207
+ "spec": spec,
208
+ "model": model.state_dict(),
209
+ "optimizer": opt.state_dict(),
210
+ "stream": stream.state_dict(),
211
+ "counts": counts,
212
+ "elapsed_training": elapsed_training,
213
+ "elapsed_eval": elapsed_eval,
214
+ "cpu_rng": torch.get_rng_state(),
215
+ "cuda_rng": torch.cuda.get_rng_state(device),
216
+ }
217
+ torch.save(state, out / "latest.tmp.pt")
218
+ (out / "latest.tmp.pt").replace(checkpoint)
219
+ if step in spec["weight_nodes"]:
220
+ torch.save(
221
+ {"spec": spec, "step": step, "model": model.state_dict()},
222
+ out / f"weights-{step:07d}.pt",
223
+ )
224
+ status = {
225
+ "state": "complete" if step == spec["steps"] else "running",
226
+ "step": step,
227
+ "budget": spec["steps"],
228
+ "updated_utc": utc(),
229
+ "hops": spec["hops"],
230
+ "layers": spec["layers"],
231
+ "atomic": row["atomic"]["accuracy"],
232
+ "train": row["train_composite"]["accuracy"],
233
+ "test_probe": row["test_composite"]["accuracy"],
234
+ }
235
+ write_json(out / "status.json", status)
236
+ print(json.dumps(status), flush=True)
237
+ return row
238
+
239
+ if not resume:
240
+ measure(0)
241
+ if start_step < spec["steps"]:
242
+ for end in (s for s in spec["nodes"] if s > start_step):
243
+ last_loss = None
244
+ torch.cuda.synchronize()
245
+ t0 = time.perf_counter()
246
+ step = start_step
247
+ while step < end:
248
+ n = min(512, end - step)
249
+ ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"])
250
+ atom_count = int((ix < len(world["atomic"])).sum())
251
+ counts["atomic"] += atom_count
252
+ counts["composite"] += ix.size - atom_count
253
+ gpu_ix = torch.as_tensor(ix, device=device)
254
+ for j in range(n):
255
+ lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"]))
256
+ last_loss = graph(gpu_ix[j])
257
+ step += n
258
+ torch.cuda.synchronize()
259
+ elapsed_training += time.perf_counter() - t0
260
+ loss_value = float(last_loss.detach())
261
+ if not math.isfinite(loss_value):
262
+ raise FloatingPointError(f"Nonfinite loss at step {end}")
263
+ measure(end, loss_value)
264
+ start_step = end
265
+ if not rows_log or rows_log[-1]["step"] != spec["steps"]:
266
+ raise ValueError("Evaluation nodes did not reach the fixed budget")
267
+ write_json(
268
+ out / "complete.json",
269
+ {
270
+ "finished_utc": utc(),
271
+ "spec": spec,
272
+ "parameters": nparams,
273
+ "training_seconds": elapsed_training,
274
+ "evaluation_seconds": elapsed_eval,
275
+ "endpoint": rows_log[-1],
276
+ },
277
+ )
278
+ return rows_log[-1]
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop_data.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Separate longer-path extension of the audited two-hop random-world task.
2
+
3
+ The graph and atomic split are reused exactly. A run trains all atomics and
4
+ one explicitly specified path length; no intermediate entities are targets.
5
+ Complete queries, not constituent facts or subpaths, define held-out examples.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import math
12
+
13
+ import numpy as np
14
+
15
+ from .grok_depth_data import ENTITY_OFFSET
16
+ from .grok_depth_data import build_world as build_twohop_world
17
+
18
+ SPLITS = (
19
+ "atomic",
20
+ "id_atomic",
21
+ "ood_atomic",
22
+ "train_composite",
23
+ "test_composite",
24
+ "test_full_composite",
25
+ "ood_composite",
26
+ "unused_composite",
27
+ )
28
+
29
+
30
+ def path_details(rows, atomic, entities, relations):
31
+ """Return the actual entity trajectory and atomic row indices at each hop."""
32
+ offset = ENTITY_OFFSET + entities
33
+ lookup = np.full((entities, relations), -1, dtype=np.int64)
34
+ lookup[atomic[:, 0] - ENTITY_OFFSET, atomic[:, 1] - offset] = np.arange(len(atomic))
35
+ nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64)
36
+ edges = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64)
37
+ nodes[:, 0] = rows[:, 0]
38
+ for j in range(edges.shape[1]):
39
+ indices = lookup[nodes[:, j] - ENTITY_OFFSET, rows[:, j + 1] - offset]
40
+ if np.any(indices < 0):
41
+ raise ValueError("Path references a missing atomic fact")
42
+ edges[:, j] = indices
43
+ nodes[:, j + 1] = atomic[indices, -1]
44
+ if np.any(nodes[:, -1] != rows[:, -1]):
45
+ raise ValueError("Path target disagrees with atomic facts")
46
+ return nodes, edges
47
+
48
+
49
+ def _diagnostics(rows, atomic, entities, relations, id_mask):
50
+ nodes, edges = path_details(rows, atomic, entities, relations)
51
+ repeated = np.zeros(len(rows), dtype=bool)
52
+ for j in range(1, nodes.shape[1]):
53
+ repeated |= (nodes[:, j, None] == nodes[:, :j]).any(axis=1)
54
+ positional = []
55
+ for j in range(edges.shape[1]):
56
+ counts = np.bincount(edges[:, j], minlength=len(atomic))
57
+ positional.append(
58
+ {
59
+ "hop": j + 1,
60
+ "id_edges_covered": int((counts[id_mask] > 0).sum()),
61
+ "id_edges_total": int(id_mask.sum()),
62
+ "counts_per_atomic_edge": counts.tolist(),
63
+ "id_count_min": int(counts[id_mask].min()) if id_mask.any() else None,
64
+ "id_count_max": int(counts[id_mask].max()) if id_mask.any() else None,
65
+ }
66
+ )
67
+ return {
68
+ "n": len(rows),
69
+ "any_repeated_entity_n": int(repeated.sum()),
70
+ "any_repeated_entity_fraction": float(repeated.mean()) if len(rows) else None,
71
+ "answer_equals_preceding_entity_n": int(
72
+ (nodes[:, -1, None] == nodes[:, :-1]).any(axis=1).sum()
73
+ ),
74
+ "edge_positions": positional,
75
+ }
76
+
77
+
78
+ def build_world(
79
+ seed,
80
+ hops=3,
81
+ entities=128,
82
+ relations=16,
83
+ degree=8,
84
+ phi=6.0,
85
+ id_fraction=0.95,
86
+ id_test_fraction=0.1,
87
+ evaluation_size=1024,
88
+ ):
89
+ """Enumerate all paths, reserve test queries, then sample training queries.
90
+
91
+ The fixed per-node evaluation subset is sampled from the entire reserved
92
+ test pool without consulting training or predictions. Endpoints evaluate
93
+ that full pool too. Mixed-ID/OOD paths remain excluded, as before.
94
+ """
95
+ if not isinstance(hops, int) or isinstance(hops, bool) or not 2 <= hops <= 4:
96
+ raise ValueError("hops must be an integer from 2 through 4")
97
+ if not isinstance(evaluation_size, int) or evaluation_size < 1:
98
+ raise ValueError("evaluation_size must be a positive integer")
99
+ if not math.isfinite(phi) or phi < 0:
100
+ raise ValueError("phi must be finite and nonnegative")
101
+ base = build_twohop_world(seed, entities, relations, degree, 0.0, id_fraction, id_test_fraction)
102
+ atomic = base["atomic"]
103
+ ood_set = {tuple(row) for row in base["ood_atomic"]}
104
+ ood_mask = np.array([tuple(row) in ood_set for row in atomic])
105
+ rows = atomic.copy()
106
+ all_id, all_ood = ~ood_mask, ood_mask.copy()
107
+ for _ in range(1, hops):
108
+ following = (rows[:, -1, None] - ENTITY_OFFSET) * degree + np.arange(degree)
109
+ following = following.reshape(-1)
110
+ prefix = np.repeat(rows[:, :-1], degree, axis=0)
111
+ rows = np.c_[prefix, atomic[following, 1:]]
112
+ all_id = np.repeat(all_id, degree) & ~ood_mask[following]
113
+ all_ood = np.repeat(all_ood, degree) & ood_mask[following]
114
+ id_rows = rows[all_id]
115
+ rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144001]))
116
+ test_mask = rng.random(len(id_rows)) < id_test_fraction
117
+ test_full = id_rows[test_mask]
118
+ eligible = id_rows[~test_mask]
119
+ probe_rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144002]))
120
+ probe_indices = probe_rng.choice(
121
+ len(test_full), size=min(evaluation_size, len(test_full)), replace=False
122
+ )
123
+ requested = round(phi * len(base["id_atomic"]))
124
+ ntrain = min(requested, len(eligible))
125
+ indices = rng.choice(len(eligible), size=ntrain, replace=False)
126
+ train_mask = np.zeros(len(eligible), dtype=bool)
127
+ train_mask[indices] = True
128
+ world = {
129
+ "atomic": atomic,
130
+ "id_atomic": base["id_atomic"],
131
+ "ood_atomic": base["ood_atomic"],
132
+ "train_composite": eligible[indices],
133
+ "test_composite": test_full[probe_indices],
134
+ "test_full_composite": test_full,
135
+ "ood_composite": rows[all_ood],
136
+ "unused_composite": eligible[~train_mask],
137
+ "metadata": {
138
+ **base["metadata"],
139
+ "hops": hops,
140
+ "task": "all atomic facts plus one target composition length",
141
+ "phi_requested": phi,
142
+ "phi_actual": ntrain / max(len(base["id_atomic"]), 1),
143
+ "train_composite_requested": requested,
144
+ "train_composite_capped": requested > len(eligible),
145
+ "id_paths_total": len(id_rows),
146
+ "all_paths_total": len(rows),
147
+ "mixed_composite_excluded": int((~all_id & ~all_ood).sum()),
148
+ "training_fraction_of_id_paths": ntrain / max(len(id_rows), 1),
149
+ "training_fraction_of_nonreserved_id_paths": ntrain / max(len(eligible), 1),
150
+ "evaluation_size_requested": evaluation_size,
151
+ "probe_indices_in_full_test": probe_indices.tolist(),
152
+ "split_rng": "default_rng(SeedSequence([world_seed,hops,144001]))",
153
+ "probe_rng": "default_rng(SeedSequence([world_seed,hops,144002]))",
154
+ "construction_differences": [
155
+ "same graph and atomic split as historical two-hop constructor",
156
+ "enumerated target length 2/3/4; only one length enters a run",
157
+ "fresh deterministic complete-path reserve and phi downsampling",
158
+ "fixed test probe at every node; entire reserve evaluated at endpoint",
159
+ ],
160
+ "warnings": [
161
+ warning
162
+ for condition, warning in (
163
+ (not len(test_full), "No reserved ID paths; never regenerate the world"),
164
+ (not int(all_ood.sum()), "No all-OOD paths; report zero denominator"),
165
+ (requested > len(eligible), "Training request capped at eligible pool"),
166
+ )
167
+ if condition
168
+ ],
169
+ },
170
+ }
171
+ audit = audit_world(world)
172
+ world["metadata"]["counts"] = audit["counts"]
173
+ world["metadata"]["dataset_sha256"] = audit["dataset_sha256"]
174
+ world["metadata"]["diagnostics"] = {
175
+ name: _diagnostics(world[name], atomic, entities, relations, ~ood_mask)
176
+ for name in ("train_composite", "test_composite", "test_full_composite")
177
+ }
178
+ return world
179
+
180
+
181
+ def audit_world(world):
182
+ """Independent graph truth, split completeness and full-query leakage checks."""
183
+ meta = world["metadata"]
184
+ entities, relations, hops = (int(meta[k]) for k in ("entities", "relations", "hops"))
185
+ offset = ENTITY_OFFSET + entities
186
+ digest = hashlib.sha256()
187
+ counts = {}
188
+ for name in SPLITS:
189
+ rows = world[name]
190
+ columns = 3 if name.endswith("atomic") else hops + 2
191
+ if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != columns:
192
+ raise ValueError(f"Invalid shape or dtype: {name}")
193
+ if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= offset)):
194
+ raise ValueError(f"Invalid entity tokens: {name}")
195
+ if np.any((rows[:, 1:-1] < offset) | (rows[:, 1:-1] >= offset + relations)):
196
+ raise ValueError(f"Invalid relation tokens: {name}")
197
+ if len(np.unique(rows[:, :-1], axis=0)) != len(rows):
198
+ raise ValueError(f"Duplicate complete queries: {name}")
199
+ path_details(rows, world["atomic"], entities, relations)
200
+ counts[name] = len(rows)
201
+ digest.update(name.encode())
202
+ digest.update(np.asarray(rows.shape, dtype="<i8").tobytes())
203
+ digest.update(rows.astype("<i8", copy=False).tobytes())
204
+ atoms = {tuple(row) for row in world["atomic"]}
205
+ ids = {tuple(row) for row in world["id_atomic"]}
206
+ oods = {tuple(row) for row in world["ood_atomic"]}
207
+ if ids & oods or ids | oods != atoms:
208
+ raise ValueError("Atomic ID/OOD split is not a partition")
209
+ is_id = np.array([tuple(row) in ids for row in world["atomic"]])
210
+ primary = ("train_composite", "test_full_composite", "unused_composite", "ood_composite")
211
+ joined = np.concatenate([world[name] for name in primary])
212
+ if len(np.unique(joined[:, :-1], axis=0)) != len(joined):
213
+ raise ValueError("Complete queries overlap across train/reserve/unused/OOD")
214
+ for name in primary:
215
+ _, edges = path_details(world[name], world["atomic"], entities, relations)
216
+ expected = ~is_id[edges] if name == "ood_composite" else is_id[edges]
217
+ if not expected.all():
218
+ raise ValueError(f"Incorrect atomic split along path: {name}")
219
+ lookup = np.zeros((entities, relations), dtype=np.int64)
220
+ id_lookup = lookup.copy()
221
+ atomic = world["atomic"]
222
+ for mask, table in ((is_id, id_lookup), (~is_id, lookup)):
223
+ table.fill(-1)
224
+ table[atomic[mask, 0] - ENTITY_OFFSET, atomic[mask, 1] - offset] = (
225
+ atomic[mask, -1] - ENTITY_OFFSET
226
+ )
227
+ totals = []
228
+ for table in (id_lookup, lookup):
229
+ path_counts = np.ones(entities, dtype=np.int64)
230
+ for _ in range(hops):
231
+ path_counts = np.where(table >= 0, path_counts[np.maximum(table, 0)], 0).sum(1)
232
+ totals.append(int(path_counts.sum()))
233
+ if sum(counts[k] for k in primary[:3]) != totals[0] or counts[primary[3]] != totals[1]:
234
+ raise ValueError("Path partitions are not exhaustive")
235
+ probes = np.asarray(meta["probe_indices_in_full_test"], dtype=np.int64)
236
+ if not np.array_equal(world["test_composite"], world["test_full_composite"][probes]):
237
+ raise ValueError("Fixed test probe differs from its recorded full-pool indices")
238
+ return {
239
+ "counts": counts,
240
+ "dataset_sha256": digest.hexdigest(),
241
+ "id_paths_independently_counted": totals[0],
242
+ "ood_paths_independently_counted": totals[1],
243
+ "complete_query_overlap": 0,
244
+ "atomic_facts_intentionally_shared_with_test": True,
245
+ }
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_data.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired fact-use assignments and constituent-occurrence repetition controls.
2
+
3
+ The same random graph and held-out queries are used in every arm. A/B change
4
+ which random fact cohort may occur in composition training. repA/repB replace
5
+ each selected role-composition slot with its two constituent atomic queries;
6
+ their half-weight losses preserve slot weight, not information or computation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import hashlib
13
+ from collections.abc import Mapping
14
+
15
+ import numpy as np
16
+
17
+ from .grok_depth_data import build_world as build_graph_world
18
+ from .grok_loop_data import _EpochStream
19
+
20
+ GROUP_NAMES = ("BG", "A", "B")
21
+ ARMS = ("A", "B", "repA", "repB")
22
+ ROW_KINDS = ("base_atomic", "background_composite", "role_composite", "repetition_atomic")
23
+
24
+
25
+ def _digest(arrays: Mapping[str, np.ndarray]) -> str:
26
+ digest = hashlib.sha256()
27
+ for name in sorted(arrays):
28
+ array = np.asarray(arrays[name], dtype="<i8")
29
+ digest.update(name.encode())
30
+ digest.update(np.asarray(array.shape, dtype="<i8").tobytes())
31
+ digest.update(array.tobytes())
32
+ return digest.hexdigest()
33
+
34
+
35
+ def _fact_counts(indices: np.ndarray, n_atomic: int) -> np.ndarray:
36
+ return np.bincount(indices[indices >= 0], minlength=n_atomic).astype(np.int64)
37
+
38
+
39
+ def build_experiment(spec: Mapping) -> dict:
40
+ """Build one graph, one global reserve, and paired composition pools.
41
+
42
+ Defaults are 128 entities, 16 relations, outdegree 8, and a 10% Bernoulli
43
+ complete-query reserve. A/B cohorts each contain floor(n_atomic/4) facts;
44
+ all remaining facts form the shared background. Cohort assignment and the
45
+ reserve have independent RNGs and never depend on predictions. Role pools
46
+ are uniformly downsampled to their smaller available size. Background
47
+ paths are used exhaustively. Empty sampled strata raise without resampling.
48
+ """
49
+ seed = int(spec.get("world_seed", spec.get("seed", 146001)))
50
+ entities = int(spec.get("entities", 128))
51
+ relations = int(spec.get("relations", 16))
52
+ degree = int(spec.get("degree", 8))
53
+ reserve_fraction = float(spec.get("test_fraction", 0.1))
54
+ if spec.get("hops", 2) != 2:
55
+ raise ValueError("This comparison is defined only for two hops")
56
+ if not np.isfinite(reserve_fraction) or not 0 < reserve_fraction < 1:
57
+ raise ValueError("test_fraction must lie strictly between zero and one")
58
+ base = build_graph_world(
59
+ seed, entities, relations, degree, phi=0, id_fraction=1, id_test_fraction=0
60
+ )
61
+ atomic = base["atomic"].copy()
62
+ n_atomic = len(atomic)
63
+ cohort_size = n_atomic // 4
64
+ if not cohort_size:
65
+ raise ValueError("At least four atomic facts are required")
66
+ # All paths use the stable per-head block ordering of the inherited graph.
67
+ second = ((atomic[:, -1, None] - 2) * degree + np.arange(degree)).reshape(-1)
68
+ first = np.repeat(np.arange(n_atomic, dtype=np.int64), degree)
69
+ all_edges = np.c_[first, second]
70
+ all_rows = np.c_[atomic[first, :2], atomic[second, 1:]]
71
+ reserve_rng = np.random.default_rng(np.random.SeedSequence([seed, 146101]))
72
+ heldout = reserve_rng.random(len(all_rows)) < reserve_fraction
73
+ assignment_rng = np.random.default_rng(np.random.SeedSequence([seed, 146102]))
74
+ assignment = assignment_rng.permutation(n_atomic)
75
+ groups = np.zeros(n_atomic, dtype=np.int64)
76
+ groups[assignment[:cohort_size]] = 1
77
+ groups[assignment[cohort_size : 2 * cohort_size]] = 2
78
+ path_groups = groups[all_edges]
79
+ background_indices = np.flatnonzero(~heldout & (path_groups == 0).all(axis=1))
80
+ role_candidates = {}
81
+ for name, group in (("A", 1), ("B", 2)):
82
+ eligible = ((path_groups == 0) | (path_groups == group)).all(axis=1)
83
+ role_candidates[name] = np.flatnonzero(
84
+ ~heldout & eligible & (path_groups == group).any(axis=1)
85
+ )
86
+ role_size = min(map(len, role_candidates.values()))
87
+ if not len(background_indices) or not role_size:
88
+ raise ValueError("Empty training stratum; retain the supplied world, do not reroll")
89
+ selected = {}
90
+ for name, group in (("A", 1), ("B", 2)):
91
+ rng = np.random.default_rng(np.random.SeedSequence([seed, 146103, group]))
92
+ selected[name] = rng.choice(role_candidates[name], size=role_size, replace=False)
93
+ exp = {
94
+ "atomic": atomic,
95
+ "fact_groups": groups,
96
+ "all_composite": all_rows,
97
+ "all_composite_fact_indices": all_edges,
98
+ "heldout_mask": heldout,
99
+ "test_composite": all_rows[heldout],
100
+ "test_composite_fact_indices": all_edges[heldout],
101
+ "background_composite": all_rows[background_indices],
102
+ "background_fact_indices": all_edges[background_indices],
103
+ "role_A_composite": all_rows[selected["A"]],
104
+ "role_A_fact_indices": all_edges[selected["A"]],
105
+ "role_B_composite": all_rows[selected["B"]],
106
+ "role_B_fact_indices": all_edges[selected["B"]],
107
+ "metadata": {
108
+ "world_seed": seed,
109
+ "seed": seed,
110
+ "entities": entities,
111
+ "relations": relations,
112
+ "degree": degree,
113
+ "hops": 2,
114
+ "vocab_size": 2 + entities + relations,
115
+ "test_fraction": reserve_fraction,
116
+ "cohort_assignment_rng": "SeedSequence([world_seed,146102])",
117
+ "complete_query_reserve_rng": "SeedSequence([world_seed,146101])",
118
+ "role_pool_rng": "SeedSequence([world_seed,146103,group])",
119
+ "group_names": list(GROUP_NAMES),
120
+ "group_sizes": [int((groups == group).sum()) for group in range(3)],
121
+ "role_candidate_sizes": {name: len(rows) for name, rows in role_candidates.items()},
122
+ "role_pool_size": role_size,
123
+ "background_pool_size": len(background_indices),
124
+ "test_queries": int(heldout.sum()),
125
+ "all_queries": len(all_rows),
126
+ "source_graph_sha256": base["metadata"]["dataset_sha256"],
127
+ "source_graph_constructor": "grok_depth_data.build_world (atomic graph only)",
128
+ "role_meaning": "random eligibility; actual per-fact occurrence counts also reported",
129
+ "selection": "one supplied graph; no data or model-score based seed selection",
130
+ },
131
+ }
132
+ for name in ("background", "role_A", "role_B"):
133
+ counts = _fact_counts(exp[name + "_fact_indices"], n_atomic)
134
+ exp["metadata"][name + "_fact_occurrence_counts"] = counts.tolist()
135
+ exp["metadata"]["test_group_counts"] = {
136
+ f"{left}_{right}": int(
137
+ (heldout & (path_groups[:, 0] == i) & (path_groups[:, 1] == j)).sum()
138
+ )
139
+ for i, left in enumerate(GROUP_NAMES)
140
+ for j, right in enumerate(GROUP_NAMES)
141
+ }
142
+ audit = audit_experiment(exp)
143
+ exp["metadata"]["dataset_sha256"] = audit["dataset_sha256"]
144
+ return exp
145
+
146
+
147
+ def audit_experiment(exp: dict) -> dict:
148
+ """Reconstruct truth and verify the global reserve and swapped eligibility."""
149
+ atomic, groups, meta = exp["atomic"], exp["fact_groups"], exp["metadata"]
150
+ if atomic.dtype != np.int64 or groups.dtype != np.int64 or len(groups) != len(atomic):
151
+ raise ValueError("Invalid atomic or group arrays")
152
+ if np.any((groups < 0) | (groups > 2)):
153
+ raise ValueError("Invalid fact group")
154
+ lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atomic)}
155
+ if len(lookup) != len(atomic):
156
+ raise ValueError("Duplicate atomic queries")
157
+ heldout_queries = {tuple(row[:-1]) for row in exp["test_composite"]}
158
+ if len(heldout_queries) != len(exp["test_composite"]):
159
+ raise ValueError("Duplicate held-out query")
160
+ arrays = {"atomic": atomic, "fact_groups": groups}
161
+ for name in ("all", "test", "background", "role_A", "role_B"):
162
+ rows = exp[name + "_composite"]
163
+ index_key = (
164
+ name + "_composite_fact_indices" if name in ("all", "test") else name + "_fact_indices"
165
+ )
166
+ recorded = exp[index_key]
167
+ expected = np.empty((len(rows), 2), dtype=np.int64)
168
+ seen = set()
169
+ for i, (h, r1, r2, t) in enumerate(rows):
170
+ query = (int(h), int(r1), int(r2))
171
+ if query in seen:
172
+ raise ValueError(f"Duplicate query in {name}")
173
+ seen.add(query)
174
+ try:
175
+ bridge, first = lookup[int(h), int(r1)]
176
+ target, second = lookup[bridge, int(r2)]
177
+ except KeyError as error:
178
+ raise ValueError(f"Missing path fact in {name}") from error
179
+ if target != t:
180
+ raise ValueError(f"Wrong path target in {name}")
181
+ expected[i] = first, second
182
+ if name in ("background", "role_A", "role_B") and query in heldout_queries:
183
+ raise ValueError("Held-out query leaked into training")
184
+ if not np.array_equal(recorded, expected):
185
+ raise ValueError(f"Incorrect fact indices in {name}")
186
+ if name == "background" and np.any(groups[expected] != 0):
187
+ raise ValueError("Background pool uses a treatment fact")
188
+ if name in ("role_A", "role_B"):
189
+ role = 1 if name == "role_A" else 2
190
+ actual_groups = groups[expected]
191
+ if np.any((actual_groups != 0) & (actual_groups != role)):
192
+ raise ValueError("Role pool uses the opposite cohort")
193
+ if np.any(~(actual_groups == role).any(axis=1)):
194
+ raise ValueError("Role pool contains a background-only path")
195
+ arrays[name] = rows
196
+ arrays[index_key] = recorded
197
+ if len(exp["all_composite"]) != len(atomic) * int(meta["degree"]):
198
+ raise ValueError("Incomplete full path enumeration")
199
+ if not np.array_equal(exp["all_composite"][exp["heldout_mask"]], exp["test_composite"]):
200
+ raise ValueError("Global held-out mask disagrees with test queries")
201
+ if len(exp["role_A_composite"]) != len(exp["role_B_composite"]):
202
+ raise ValueError("Paired role pools differ in size")
203
+ digest = _digest(arrays)
204
+ recorded_digest = meta.get("dataset_sha256")
205
+ if recorded_digest is not None and recorded_digest != digest:
206
+ raise ValueError("Recorded dataset hash differs from arrays")
207
+ return {"passed": True, "dataset_sha256": digest, "test_queries": len(heldout_queries)}
208
+
209
+
210
+ def build_arm_world(exp: dict, arm: str) -> dict:
211
+ """Return packed-table ingredients, evaluation sets and exposure provenance.
212
+
213
+ Concatenate ``pack_rows(part['rows'], 4)`` in ``training_parts`` order.
214
+ ``table_weights`` and ``table_fact_indices`` align with that concatenation.
215
+ An atomic row has one fact id and -1; a composition row has two ids. Thus
216
+ raw fact occurrences can be accumulated without interpreting token counts
217
+ or claiming equal supervision/information. rep arms keep the same role
218
+ path reference pool for paired evaluation, but do not train those queries.
219
+ """
220
+ if arm not in ARMS:
221
+ raise ValueError(f"Unknown arm: {arm}")
222
+ role_name = arm[-1]
223
+ repeat = arm.startswith("rep")
224
+ atomic = exp["atomic"]
225
+ n_atomic = len(atomic)
226
+ atom_indices = np.c_[np.arange(n_atomic), np.full(n_atomic, -1)].astype(np.int64)
227
+ role_edges = exp[f"role_{role_name}_fact_indices"]
228
+ role_rows = exp[f"role_{role_name}_composite"]
229
+ if repeat:
230
+ last_rows = atomic[role_edges.ravel()]
231
+ last_edges = np.c_[role_edges.ravel(), np.full(role_edges.size, -1)].astype(np.int64)
232
+ else:
233
+ last_rows, last_edges = role_rows, role_edges
234
+ parts = [
235
+ {
236
+ "name": "atomic",
237
+ "rows": atomic,
238
+ "weights": np.ones(n_atomic, dtype=np.float32),
239
+ "fact_indices": atom_indices,
240
+ },
241
+ {
242
+ "name": "background",
243
+ "rows": exp["background_composite"],
244
+ "weights": np.ones(len(exp["background_composite"]), dtype=np.float32),
245
+ "fact_indices": exp["background_fact_indices"],
246
+ },
247
+ {
248
+ "name": "repetition" if repeat else "role",
249
+ "rows": last_rows,
250
+ "weights": np.full(len(last_rows), 0.5 if repeat else 1, dtype=np.float32),
251
+ "fact_indices": last_edges,
252
+ },
253
+ ]
254
+ evaluation = {"atomic": atomic}
255
+ for group, name in enumerate(GROUP_NAMES):
256
+ evaluation[f"atomic_{name}"] = atomic[exp["fact_groups"] == group]
257
+ evaluation["test_composite"] = exp["test_composite"]
258
+ query_groups = exp["fact_groups"][exp["test_composite_fact_indices"]]
259
+ for i, left in enumerate(GROUP_NAMES):
260
+ for j, right in enumerate(GROUP_NAMES):
261
+ mask = (query_groups[:, 0] == i) & (query_groups[:, 1] == j)
262
+ evaluation[f"test_{left}_{right}"] = exp["test_composite"][mask]
263
+ evaluation["train_background"] = exp["background_composite"]
264
+ evaluation["role_A_reference"] = exp["role_A_composite"]
265
+ evaluation["role_B_reference"] = exp["role_B_composite"]
266
+ train_composite = (
267
+ exp["background_composite"]
268
+ if repeat
269
+ else np.concatenate([exp["background_composite"], role_rows])
270
+ )
271
+ evaluation["train_composite"] = train_composite
272
+ group_id = 1 if role_name == "A" else 2
273
+ eligible = (exp["fact_groups"] == 0) | ((exp["fact_groups"] == group_id) & (not repeat))
274
+ used_counts = _fact_counts(
275
+ np.concatenate(
276
+ [exp["background_fact_indices"], role_edges if not repeat else role_edges[:0]]
277
+ ),
278
+ n_atomic,
279
+ )
280
+ world = {
281
+ "arm": arm,
282
+ "atomic": atomic,
283
+ "id_atomic": atomic[eligible],
284
+ "ood_atomic": atomic[~eligible],
285
+ "background_composite": exp["background_composite"],
286
+ "role_composite": role_rows,
287
+ "train_composite": train_composite,
288
+ "test_composite": exp["test_composite"],
289
+ "test_full_composite": exp["test_composite"],
290
+ "training_parts": parts,
291
+ "table_weights": np.concatenate([part["weights"] for part in parts]),
292
+ "table_fact_indices": np.concatenate([part["fact_indices"] for part in parts]),
293
+ "table_row_kinds": np.concatenate(
294
+ [
295
+ np.full(len(part["rows"]), kind, dtype=np.int64)
296
+ for part, kind in zip(parts, [0, 1, 3 if repeat else 2], strict=True)
297
+ ]
298
+ ),
299
+ "evaluation": evaluation,
300
+ "metadata": {
301
+ **copy.deepcopy(exp["metadata"]),
302
+ "arm": arm,
303
+ "repetition_control": repeat,
304
+ "role_name": role_name,
305
+ "row_kind_names": list(ROW_KINDS),
306
+ "training_composite_fact_occurrence_counts": used_counts.tolist(),
307
+ "eligible_facts_without_actual_composite_occurrence": int(
308
+ (eligible & (used_counts == 0)).sum()
309
+ ),
310
+ "evaluation_note": "same global heldout and nine cohort-pair strata in every arm",
311
+ "repetition_note": (
312
+ "two constituent atomics per role slot, each loss weight 1/2; matches raw "
313
+ "constituent occurrences, not information, direct supervision or compute"
314
+ ),
315
+ },
316
+ }
317
+ return world
318
+
319
+
320
+ class UsageStream:
321
+ """Emit paired base/background/role slots, expanding rep slots into two rows."""
322
+
323
+ def __init__(self, world, seed, n_atomic=32, n_background=112, n_role=112):
324
+ for name, value in (
325
+ ("n_atomic", n_atomic),
326
+ ("n_background", n_background),
327
+ ("n_role", n_role),
328
+ ):
329
+ if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1:
330
+ raise ValueError(f"{name} must be a positive integer")
331
+ self.arm = world["arm"]
332
+ self.repeat = self.arm.startswith("rep")
333
+ self.atomic_size = len(world["atomic"])
334
+ self.background_size = len(world["background_composite"])
335
+ self.role_size = len(world["role_composite"])
336
+ self.n_atomic, self.n_background, self.n_role = (
337
+ int(n_atomic),
338
+ int(n_background),
339
+ int(n_role),
340
+ )
341
+ if min(self.atomic_size, self.background_size, self.role_size) < 1:
342
+ raise ValueError("Sampled strata cannot be empty")
343
+ self.nominal_batch_size = self.n_atomic + self.n_background + self.n_role
344
+ self.batch_size = self.nominal_batch_size + (self.n_role if self.repeat else 0)
345
+ self.atomic = _EpochStream(self.atomic_size, np.random.SeedSequence([int(seed), 146201]))
346
+ self.background = _EpochStream(
347
+ self.background_size, np.random.SeedSequence([int(seed), 146202])
348
+ )
349
+ self.role = _EpochStream(self.role_size, np.random.SeedSequence([int(seed), 146203]))
350
+ self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 146204]))
351
+ self.batches = 0
352
+
353
+ def take(self, n=None):
354
+ if n is not None and n != self.batch_size:
355
+ raise ValueError("UsageStream emits its configured actual batch size")
356
+ atoms = self.atomic.take(self.n_atomic)
357
+ background = self.background.take(self.n_background) + self.atomic_size
358
+ role = self.role.take(self.n_role)
359
+ if self.repeat:
360
+ role = (role[:, None] * 2 + np.arange(2)).ravel()
361
+ role = role + self.atomic_size + self.background_size
362
+ indices = np.r_[atoms, background, role]
363
+ self.batches += 1
364
+ return indices[self.interleave.permutation(self.batch_size)]
365
+
366
+ def state_dict(self):
367
+ return {
368
+ "version": 1,
369
+ "arm": self.arm,
370
+ "n_atomic": self.n_atomic,
371
+ "n_background": self.n_background,
372
+ "n_role": self.n_role,
373
+ "atomic": self.atomic.state_dict(),
374
+ "background": self.background.state_dict(),
375
+ "role": self.role.state_dict(),
376
+ "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state),
377
+ "batches": self.batches,
378
+ }
379
+
380
+ def load_state_dict(self, state):
381
+ if state.get("version") != 1:
382
+ raise ValueError("Unsupported UsageStream state version")
383
+ for name in ("arm", "n_atomic", "n_background", "n_role"):
384
+ if state[name] != getattr(self, name):
385
+ raise ValueError(f"UsageStream {name} mismatch")
386
+ if not isinstance(state["batches"], int) or state["batches"] < 0:
387
+ raise ValueError("Invalid batch count")
388
+ replacements = {}
389
+ for name in ("atomic", "background", "role"):
390
+ replacements[name] = copy.deepcopy(getattr(self, name))
391
+ replacements[name].load_state_dict(state[name])
392
+ interleave = copy.deepcopy(self.interleave)
393
+ interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"])
394
+ for name, stream in replacements.items():
395
+ setattr(self, name, stream)
396
+ self.interleave = interleave
397
+ self.batches = state["batches"]
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_train.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired training of composition experience versus constituent-fact repetition."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch.nn import functional as F
13
+
14
+ from .bios_model import ModelConfig
15
+ from .grok_depth import GraphStep, make_optimizer, utc, write_json
16
+ from .grok_loop_model import LoopGPT, flops
17
+ from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows
18
+ from .grok_usage_data import UsageStream
19
+
20
+
21
+ def weighted_loss(logits, labels, weights, normalizer):
22
+ """Each logical slot has weight one; its two atomic substitutes have .5 each."""
23
+ losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none")
24
+ return (losses.view(-1, 2).mean(1) * weights).sum() / normalizer
25
+
26
+
27
+ class UsageGraphStep(GraphStep):
28
+ def __init__(self, model, optimizer, table, batch_size, normalizer):
29
+ self.normalizer = normalizer
30
+ super().__init__(model, optimizer, table, batch_size)
31
+
32
+ def eager(self):
33
+ self.optimizer.zero_grad(set_to_none=False)
34
+ x, positions, labels, weights = (t[self.index] for t in self.table)
35
+ loss = weighted_loss(self.model(x, positions), labels, weights, self.normalizer)
36
+ loss.backward()
37
+ norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
38
+ self.optimizer.step()
39
+ return loss, norm
40
+
41
+
42
+ def make_model(spec, device):
43
+ cfg = ModelConfig(
44
+ vocab_size=2 + spec["entities"] + spec["relations"],
45
+ width=spec["width"],
46
+ layers=spec["layers"],
47
+ heads=spec["heads"],
48
+ context=8,
49
+ )
50
+ return LoopGPT(
51
+ cfg,
52
+ repeats=spec["repeats"],
53
+ dropout=spec["dropout"],
54
+ initialization=spec["init_scheme"],
55
+ ).to(device), cfg
56
+
57
+
58
+ def run(spec, world, out, device="cuda:0", resume=False):
59
+ out = Path(out)
60
+ torch.set_num_threads(1)
61
+ torch.set_num_interop_threads(1)
62
+ torch.backends.cuda.matmul.allow_tf32 = True
63
+ torch.backends.cudnn.allow_tf32 = True
64
+ device = torch.device(device)
65
+ torch.cuda.set_device(device)
66
+ torch.cuda.set_per_process_memory_fraction(spec.get("memory_fraction", 0.025), device)
67
+ torch.manual_seed(spec["initialization"])
68
+ torch.cuda.manual_seed_all(spec["initialization"])
69
+ model, cfg = make_model(spec, device)
70
+ lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device)
71
+ optimizer = make_optimizer(model, lr, spec["weight_decay"])
72
+ packed = [pack_rows(part["rows"], 4) for part in world["training_parts"]]
73
+ table = tuple(
74
+ torch.as_tensor(np.concatenate([part[j] for part in packed]), device=device)
75
+ for j in range(3)
76
+ ) + (torch.as_tensor(world["table_weights"], device=device, dtype=torch.float32),)
77
+ stream = UsageStream(
78
+ world,
79
+ spec["stream_seed"],
80
+ n_atomic=spec["n_atomic"],
81
+ n_background=spec["n_background"],
82
+ n_role=spec["n_role"],
83
+ )
84
+ logical_batch = spec["n_atomic"] + spec["n_background"] + spec["n_role"]
85
+ actual_batch = logical_batch + (spec["n_role"] if spec["arm"].startswith("rep") else 0)
86
+ exposure = np.zeros((4, len(world["atomic"])), dtype=np.int64)
87
+ kind_counts = np.zeros(4, dtype=np.int64)
88
+ train_seconds, evaluation_seconds, start_step = 0.0, 0.0, 0
89
+ if resume:
90
+ state = torch.load(out / "latest.pt", map_location=device, weights_only=False)
91
+ if state["spec"] != spec:
92
+ raise ValueError("Resume specification changed")
93
+ model.load_state_dict(state["model"])
94
+ optimizer.load_state_dict(state["optimizer"])
95
+ lr = optimizer.param_groups[0]["lr"]
96
+ for group in optimizer.param_groups:
97
+ group["lr"] = lr
98
+ stream.load_state_dict(state["stream"])
99
+ exposure, kind_counts = state["exposure"], state["kind_counts"]
100
+ train_seconds, evaluation_seconds = state["training_seconds"], state["evaluation_seconds"]
101
+ start_step = state["step"]
102
+ torch.set_rng_state(state["cpu_rng"].cpu())
103
+ torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
104
+ t0 = time.perf_counter()
105
+ graph = UsageGraphStep(model, optimizer, table, actual_batch, logical_batch)
106
+ capture_seconds = time.perf_counter() - t0
107
+ learning = json.loads((out / "learning.json").read_text()) if resume else []
108
+ learning = [row for row in learning if row["step"] <= start_step]
109
+ fact_ids = np.asarray(world["table_fact_indices"])
110
+ kinds = np.asarray(world["table_row_kinds"])
111
+ flop_step = flops(cfg, spec["repeats"], actual_batch, sequence=4, output_positions=2)
112
+
113
+ def measure(step, last_loss=None):
114
+ nonlocal evaluation_seconds
115
+ torch.cuda.synchronize()
116
+ before = time.perf_counter()
117
+ metrics, predictions = {}, {}
118
+ for name, rows in world["evaluation"].items():
119
+ metrics[name], pred = evaluate_rows(model, rows, device, 4)
120
+ if len(rows):
121
+ metrics[name]["answer_probability"] = float(np.exp(-pred["nll"][:, 0]).mean())
122
+ predictions.update({name + "_" + k: v for k, v in pred.items()})
123
+ metrics["autonomous_calls"], pred = autonomous_calls(
124
+ model,
125
+ world["evaluation"]["test_composite"],
126
+ world,
127
+ device,
128
+ 4,
129
+ )
130
+ predictions.update({"autonomous_" + k: v for k, v in pred.items()})
131
+ torch.cuda.synchronize()
132
+ evaluation_seconds += time.perf_counter() - before
133
+ row = {
134
+ "step": step,
135
+ "utc": utc(),
136
+ "arm": spec["arm"],
137
+ "world_seed": spec["world_seed"],
138
+ "metrics": metrics,
139
+ "last_batch_loss": last_loss,
140
+ "training_seconds": train_seconds,
141
+ "evaluation_seconds": evaluation_seconds,
142
+ "capture_seconds": capture_seconds,
143
+ "actual_examples": int(kind_counts.sum()),
144
+ "logical_slots": step * logical_batch,
145
+ "supervised_tokens": int(kind_counts.sum()) * 2,
146
+ "effective_input_tokens": int((kind_counts * np.array([3, 4, 4, 3])).sum()),
147
+ "estimated_training_flops": step * flop_step,
148
+ "kind_counts": kind_counts.tolist(),
149
+ }
150
+ learning.append(row)
151
+ write_json(out / "learning.json", learning)
152
+ np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions)
153
+ np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=exposure, kinds=kind_counts)
154
+ state = {
155
+ "spec": spec,
156
+ "step": step,
157
+ "model": model.state_dict(),
158
+ "optimizer": optimizer.state_dict(),
159
+ "stream": stream.state_dict(),
160
+ "exposure": exposure,
161
+ "kind_counts": kind_counts,
162
+ "training_seconds": train_seconds,
163
+ "evaluation_seconds": evaluation_seconds,
164
+ "cpu_rng": torch.get_rng_state(),
165
+ "cuda_rng": torch.cuda.get_rng_state(device),
166
+ }
167
+ torch.save(state, out / "latest.tmp.pt")
168
+ (out / "latest.tmp.pt").replace(out / "latest.pt")
169
+ if step in spec["weight_nodes"]:
170
+ torch.save(
171
+ {"spec": spec, "step": step, "model": model.state_dict()},
172
+ out / f"weights-{step:07d}.pt",
173
+ )
174
+ status = {
175
+ "state": "trained" if step == spec["steps"] else "running",
176
+ "step": step,
177
+ "budget": spec["steps"],
178
+ "arm": spec["arm"],
179
+ "updated_utc": utc(),
180
+ "test_composite": metrics["test_composite"]["accuracy"],
181
+ "training_seconds": train_seconds,
182
+ }
183
+ write_json(out / "status.json", status)
184
+ print(json.dumps(status), flush=True)
185
+
186
+ if not resume:
187
+ measure(0)
188
+ for end in (node for node in spec["nodes"] if node > start_step):
189
+ torch.cuda.synchronize()
190
+ before = time.perf_counter()
191
+ step = start_step
192
+ while step < end:
193
+ n = min(512, end - step)
194
+ indices = np.stack([stream.take() for _ in range(n)])
195
+ selected = indices.ravel()
196
+ selected_kinds, selected_facts = kinds[selected], fact_ids[selected]
197
+ kind_counts += np.bincount(selected_kinds, minlength=4)
198
+ for kind in range(4):
199
+ facts = selected_facts[selected_kinds == kind].ravel()
200
+ exposure[kind] += np.bincount(facts[facts >= 0], minlength=exposure.shape[1])
201
+ gpu_indices = torch.as_tensor(indices, device=device)
202
+ for j in range(n):
203
+ lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"]))
204
+ loss = graph(gpu_indices[j])
205
+ step += n
206
+ torch.cuda.synchronize()
207
+ train_seconds += time.perf_counter() - before
208
+ loss_value = float(loss.detach())
209
+ if not math.isfinite(loss_value):
210
+ raise FloatingPointError(f"Nonfinite loss at {end}")
211
+ measure(end, loss_value)
212
+ start_step = end
213
+ if not learning or learning[-1]["step"] != spec["steps"]:
214
+ raise ValueError("Registered nodes did not reach endpoint")
215
+ # Reload every endpoint from disk and compare all saved per-example scores.
216
+ saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
217
+ model.load_state_dict(saved["model"])
218
+ old = np.load(out / f"predictions-{spec['steps']:07d}.npz")
219
+ errors, checks, largest_nll_difference = [], 0, 0.0
220
+ for name, rows in world["evaluation"].items():
221
+ _, pred = evaluate_rows(model, rows, device, 4)
222
+ for key, value in pred.items():
223
+ reference = old[name + "_" + key]
224
+ checks += len(value)
225
+ if key == "nll":
226
+ difference = float(np.abs(value - reference).max()) if len(value) else 0.0
227
+ largest_nll_difference = max(largest_nll_difference, difference)
228
+ ok = np.allclose(value, reference, atol=1e-6, rtol=1e-6)
229
+ else:
230
+ ok = np.array_equal(value, reference)
231
+ if not ok:
232
+ errors.append(name + "_" + key)
233
+ audit = {
234
+ "checks": checks,
235
+ "errors": errors,
236
+ "max_nll_difference": largest_nll_difference,
237
+ "method": "reload saved endpoint; all evaluation splits, identical GPU/dtype/batch shape",
238
+ }
239
+ write_json(out / "endpoint-audit.json", audit)
240
+ if errors:
241
+ raise ValueError(f"Endpoint reload failed: {errors}")
242
+ write_json(
243
+ out / "complete.json",
244
+ {
245
+ "finished_utc": utc(),
246
+ "spec": spec,
247
+ "endpoint": learning[-1],
248
+ "audit": audit,
249
+ "parameters": sum(p.numel() for p in model.parameters()),
250
+ "maximum_allocated_bytes": torch.cuda.max_memory_allocated(device),
251
+ },
252
+ )
253
+ write_json(
254
+ out / "status.json",
255
+ {
256
+ "state": "complete",
257
+ "step": spec["steps"],
258
+ "arm": spec["arm"],
259
+ "utc": utc(),
260
+ },
261
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure first-hop state interventions and held-out, local fact-update branches.
2
+
3
+ The text template's factual answer is predicted at `is`, rather than at r1.
4
+ All targets and donors are selected from the graph before model inference.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import torch
15
+ from torch.nn import functional as F
16
+
17
+ from .depth_step_mechanism import traced_forward
18
+ from .grok_depth import write_json
19
+ from .latent_scaling import model_digest
20
+ from .storage_composition import generate_rows, pack_sentences
21
+ from .text_pretrain import atomic_sentence, composite_sentence
22
+
23
+ PARAMETER = "blocks.0.mlp.down.weight"
24
+
25
+
26
+ def taught_atoms(world):
27
+ return np.concatenate([world["common_atomic"], world["anchor_atomic"]])
28
+
29
+
30
+ def update_case(world, atomic_index, group, replay_n=32, keep_n=32):
31
+ """Change one graph edge; recompute the entire two-hop affected closure."""
32
+ atoms = taught_atoms(world)
33
+ old = atoms[atomic_index].copy()
34
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
35
+ first_role = 13 <= old[1] <= 16
36
+ pool = world[group + "_test"]
37
+ if first_role:
38
+ affected = (pool[:, 0] == old[0]) & (pool[:, 1] == old[1])
39
+ relation_rows = pool[affected]
40
+ options = sorted({int(row[2]) for row in atoms if 13 <= row[1] <= 16})
41
+ # Prefer the same familiar/strict bridge bank; all successor facts must be taught.
42
+ own_bank = sorted({int(row[2]) for row in pool})
43
+ candidates = [v for v in own_bank if v != old[2]] + [
44
+ v for v in options if v != old[2] and v not in own_bank
45
+ ]
46
+ new_value = next(
47
+ v
48
+ for v in candidates
49
+ if all((v, int(row[3])) in lookup for row in relation_rows)
50
+ and any(lookup[v, int(row[3])] != row[4] for row in relation_rows)
51
+ )
52
+ else:
53
+ affected = (pool[:, 2] == old[0]) & (pool[:, 3] == old[1])
54
+ tails = sorted({int(row[2]) for row in atoms if 17 <= row[1] <= 20})
55
+ new_value = tails[(tails.index(int(old[2])) + 1) % len(tails)]
56
+ new = old.copy()
57
+ new[2] = new_value
58
+ lookup[int(new[0]), int(new[1])] = int(new[2])
59
+ tasks = {"E_new": np.asarray([new]), "E_old": np.asarray([old])}
60
+ original_d = {}
61
+ successor_keys = set()
62
+ for split in ["familiar", "strict"]:
63
+ rows = world[split + "_test"]
64
+ mask = (
65
+ ((rows[:, 0] == old[0]) & (rows[:, 1] == old[1]))
66
+ if first_role
67
+ else ((rows[:, 2] == old[0]) & (rows[:, 3] == old[1]))
68
+ )
69
+ original = rows[mask].copy()
70
+ changed = original.copy()
71
+ for row in changed:
72
+ row[2] = lookup[int(row[0]), int(row[1])]
73
+ row[4] = lookup[int(row[2]), int(row[3])]
74
+ successor_keys.add((int(row[2]), int(row[3])))
75
+ name = "D_" + split
76
+ tasks[name] = changed
77
+ original_d[name] = original
78
+ tasks["U_" + split] = rows[~mask].copy()
79
+ index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)}
80
+ successor_indices = sorted(index_lookup[key] for key in successor_keys)
81
+ successor = atoms[successor_indices].copy()
82
+ if not first_role and len(successor):
83
+ successor[(successor[:, 0] == old[0]) & (successor[:, 1] == old[1])] = new
84
+ tasks["successor_atomic"] = successor
85
+ order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i]))
86
+ excluded = {atomic_index, *successor_indices}
87
+ replay = [i for i in order if i not in excluded][:replay_n]
88
+ keep = [i for i in order if i not in excluded and i not in replay][:keep_n]
89
+ unused = [i for i in range(len(atoms)) if i not in {atomic_index, *replay, *keep}]
90
+ tasks["R_atomic"] = atoms[replay].copy()
91
+ tasks["Kdev_atomic"] = atoms[keep].copy()
92
+ tasks["U_atomic"] = atoms[unused].copy()
93
+ if len(replay) != replay_n or len(keep) != keep_n:
94
+ raise ValueError("Insufficient independent replay and calibration keep facts")
95
+ return {
96
+ "atomic_index": atomic_index,
97
+ "group": group,
98
+ "role": "first" if first_role else "second",
99
+ "old_fact": old.tolist(),
100
+ "new_fact": new.tolist(),
101
+ "replay_indices": replay,
102
+ "keep_indices": keep,
103
+ "unused_indices": unused,
104
+ "tasks": tasks,
105
+ "original_d": original_d,
106
+ }
107
+
108
+
109
+ def select_cases(world, n_per_group_role=2, calibration=False):
110
+ """Graph-defined, largest affected-pool targets; no checkpoint-dependent selection."""
111
+ atoms = taught_atoms(world)
112
+ chosen = []
113
+ groups = ["familiar"] if calibration else ["familiar", "strict"]
114
+ for group in groups:
115
+ rows = world[group + "_test"]
116
+ for role in ["first", "second"]:
117
+ counts = {}
118
+ for row in rows:
119
+ key = tuple(map(int, row[:2] if role == "first" else row[[2, 3]]))
120
+ counts[key] = counts.get(key, 0) + 1
121
+ candidates = [i for i, atom in enumerate(atoms) if tuple(map(int, atom[:2])) in counts]
122
+ candidates.sort(key=lambda i: (-counts[tuple(map(int, atoms[i, :2]))], tuple(atoms[i])))
123
+ for i in candidates[:n_per_group_role]:
124
+ chosen.append(update_case(world, i, group))
125
+ if len(chosen) != len(groups) * 2 * n_per_group_role:
126
+ raise ValueError("Not enough distinct graph-defined editor targets")
127
+ return chosen
128
+
129
+
130
+ def serialize_case(case):
131
+ return {
132
+ key: {name: rows.tolist() for name, rows in value.items()}
133
+ if key in ["tasks", "original_d"]
134
+ else value
135
+ for key, value in case.items()
136
+ }
137
+
138
+
139
+ def answer_batch(rows, device):
140
+ """Factual answer, punctuation and EOS only; random prefix targets are excluded."""
141
+ tokens, labels = pack_sentences(rows)
142
+ first = 4 if rows.shape[1] == 3 else 6
143
+ positions = np.tile([first, first + 1, first + 2], (len(rows), 1))
144
+ selected = labels[np.arange(len(rows))[:, None], positions]
145
+ np.testing.assert_array_equal(
146
+ selected, np.c_[rows[:, -1], np.full(len(rows), 5), np.ones(len(rows), dtype=np.int64)]
147
+ )
148
+ return tuple(torch.as_tensor(x, device=device) for x in [tokens, positions, selected])
149
+
150
+
151
+ def safe_generate(model, rows, device):
152
+ if len(rows):
153
+ return generate_rows(model, rows, device)
154
+ return {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, {
155
+ "generated": np.empty((0, 3), dtype=np.int64),
156
+ "correct": np.empty(0, dtype=bool),
157
+ "answer_nll": np.empty(0, dtype=np.float32),
158
+ }
159
+
160
+
161
+ def editor(model, case, device, arm, lr, nodes=(0, 200)):
162
+ """Independent local update, with parent KL reference and exact final tensor saved."""
163
+ if arm not in ["edit", "review"]:
164
+ raise ValueError("Unknown editor arm")
165
+ started = time.perf_counter()
166
+ parent_hash = model_digest(model)
167
+ edited = copy.deepcopy(model).eval()
168
+ for name, parameter in edited.named_parameters():
169
+ parameter.requires_grad_(name == PARAMETER)
170
+ parameter.grad = None
171
+ before = {key: value.detach().clone() for key, value in edited.state_dict().items()}
172
+ parameter = dict(edited.named_parameters())[PARAMETER]
173
+ optimizer = torch.optim.Adam([parameter], lr=lr)
174
+ target = answer_batch(
175
+ np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]), device
176
+ )
177
+ replay = answer_batch(case["tasks"]["R_atomic"], device)
178
+ with torch.no_grad():
179
+ parent_log = model(replay[0], positions=replay[1]).log_softmax(-1).detach()
180
+ parent_d = {
181
+ name: safe_generate(model, rows, device)[1] for name, rows in case["original_d"].items()
182
+ }
183
+ parent_old_fact_ok = safe_generate(model, case["tasks"]["E_old"], device)[1]["correct"].all()
184
+ parent_successors_ok = (
185
+ safe_generate(model, case["tasks"]["successor_atomic"], device)[1]["correct"].all()
186
+ if case["role"] == "first"
187
+ else True
188
+ )
189
+ history, raw, step = [], {}, 0
190
+ for node in nodes:
191
+ while step < node:
192
+ optimizer.zero_grad(set_to_none=True)
193
+ logits = edited(target[0], positions=target[1])
194
+ ce = F.cross_entropy(logits.flatten(0, 1), target[2].flatten())
195
+ current = edited(replay[0], positions=replay[1]).log_softmax(-1)
196
+ kl = F.kl_div(
197
+ current.flatten(0, 1),
198
+ parent_log.flatten(0, 1),
199
+ reduction="batchmean",
200
+ log_target=True,
201
+ )
202
+ loss = ce + kl
203
+ loss.backward()
204
+ optimizer.step()
205
+ step += 1
206
+ metrics = {}
207
+ for name, rows in case["tasks"].items():
208
+ metric, prediction = safe_generate(edited, rows, device)
209
+ if name in case["original_d"]:
210
+ original = case["original_d"][name]
211
+ changed = rows[:, -1] != original[:, -1]
212
+ parent_correct = parent_d[name]["correct"]
213
+ eligible = changed & parent_correct & parent_old_fact_ok & parent_successors_ok
214
+ pred = prediction["generated"]
215
+ old = (pred[:, 0] == original[:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1)
216
+ metric.update(
217
+ {
218
+ "changed_n": int(changed.sum()),
219
+ "parent_old_correct_n": int(parent_correct.sum()),
220
+ "eligible_n": int(eligible.sum()),
221
+ "changed_accuracy": float(prediction["correct"][changed].mean())
222
+ if changed.any()
223
+ else None,
224
+ "eligible_accuracy": float(prediction["correct"][eligible].mean())
225
+ if eligible.any()
226
+ else None,
227
+ "eligible_old_answer_accuracy": float(old[eligible].mean())
228
+ if eligible.any()
229
+ else None,
230
+ }
231
+ )
232
+ raw[name + "_changed"] = changed
233
+ raw[name + "_parent_correct"] = parent_correct
234
+ raw[name + "_original_rows"] = original
235
+ metrics[name] = metric
236
+ raw.update({f"step{node}_{name}_{key}": value for key, value in prediction.items()})
237
+ history.append({"step": step, "metrics": metrics})
238
+ changed_tensors = [
239
+ key for key, value in edited.state_dict().items() if not torch.equal(value, before[key])
240
+ ]
241
+ assert not set(changed_tensors) - {PARAMETER}
242
+ assert model_digest(model) == parent_hash
243
+ final = parameter.detach().cpu().clone()
244
+ record = {
245
+ "arm": arm,
246
+ "lr": lr,
247
+ "case": serialize_case(case),
248
+ "history": history,
249
+ "parent_model_sha256": parent_hash,
250
+ "final_model_sha256": model_digest(edited),
251
+ "changed_tensors": changed_tensors,
252
+ "delta_l2": float((parameter - before[PARAMETER]).norm()),
253
+ "seconds": time.perf_counter() - started,
254
+ "parent_old_target_atomic_correct": bool(parent_old_fact_ok),
255
+ "parent_new_successors_correct": bool(parent_successors_ok),
256
+ }
257
+ # Exact-tensor replay verifies every generated endpoint; no rounded delta reconstruction.
258
+ reloaded = copy.deepcopy(model).eval()
259
+ with torch.no_grad():
260
+ dict(reloaded.named_parameters())[PARAMETER].copy_(final.to(device))
261
+ assert model_digest(reloaded) == record["final_model_sha256"]
262
+ for name, rows in case["tasks"].items():
263
+ _, prediction = safe_generate(reloaded, rows, device)
264
+ for key, values in prediction.items():
265
+ reference = raw[f"step{nodes[-1]}_{name}_{key}"]
266
+ if key == "answer_nll":
267
+ np.testing.assert_allclose(values, reference, rtol=1e-5, atol=1e-5)
268
+ else:
269
+ np.testing.assert_array_equal(values, reference)
270
+ record["exact_weight_reload_passed"] = True
271
+ return record, raw, final
272
+
273
+
274
+ def select_donors(world, rows):
275
+ atoms = world["common_atomic"]
276
+ lookup = {tuple(map(int, row[:2])): int(row[2]) for row in atoms}
277
+ first = [(i, atom) for i, atom in enumerate(atoms) if 13 <= atom[1] <= 16]
278
+ first.sort(key=lambda pair: tuple(pair[1]))
279
+ records = {}
280
+ for style in ["same_bridge", "different_bridge"]:
281
+ indices, tails = [], []
282
+ for h, r1, bridge, r2, tail in rows:
283
+ eligible = [
284
+ (i, atom)
285
+ for i, atom in first
286
+ if atom[1] == r1
287
+ and atom[0] != h
288
+ and (int(atom[2]), int(r2)) in lookup
289
+ and (
290
+ (atom[2] == bridge)
291
+ if style == "same_bridge"
292
+ else (atom[2] != bridge and lookup[int(atom[2]), int(r2)] != tail)
293
+ )
294
+ ]
295
+ indices.append(eligible[0][0] if eligible else -1)
296
+ tails.append(lookup[int(eligible[0][1][2]), int(r2)] if eligible else -1)
297
+ records[style] = {"indices": np.asarray(indices), "tails": np.asarray(tails)}
298
+ return records
299
+
300
+
301
+ @torch.no_grad()
302
+ def patched_generation(model, tokens, patch):
303
+ generated = []
304
+ first_prob = None
305
+ for step in range(3):
306
+ logits, _ = traced_forward(model, tokens, patch)
307
+ if step == 0:
308
+ first_prob = logits[:, -1].softmax(-1)
309
+ answer = logits[:, -1].argmax(-1)
310
+ generated.append(answer.cpu().numpy())
311
+ tokens = torch.cat([tokens, answer[:, None]], dim=1)
312
+ return np.stack(generated, axis=1), first_prob
313
+
314
+
315
+ @torch.no_grad()
316
+ def trace(model, world, device, out):
317
+ """Two fixed, causally reachable sites; donors contain only a first-hop prefix."""
318
+ model.eval()
319
+ out = Path(out)
320
+ records, raw = [], {}
321
+ atoms = world["common_atomic"]
322
+ atom_metric, atom_prediction = generate_rows(model, atoms, device)
323
+ index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)}
324
+ for split in ["familiar", "strict"]:
325
+ rows = world[split + "_test"]
326
+ tokens = torch.as_tensor([composite_sentence(row)[:7] for row in rows], device=device)
327
+ reference = model(tokens)
328
+ logits, cache = traced_forward(model, tokens)
329
+ torch.testing.assert_close(logits, reference, rtol=1e-5, atol=2e-6)
330
+ assert torch.equal(logits.argmax(-1), reference.argmax(-1))
331
+ baseline_pred, baseline_prob = patched_generation(model, tokens, {})
332
+ raw[split + "_rows"] = rows
333
+ raw[split + "_baseline_generated"] = baseline_pred
334
+ for position in [3, 6]:
335
+ state = cache["postresidual"][0, :, position]
336
+ readout = F.linear(model.ln_final(state), model.token.weight)
337
+ bridge = torch.as_tensor(rows[:, 2], device=device)
338
+ rank = 1 + (readout > readout.gather(-1, bridge[:, None])).sum(-1)
339
+ raw[f"{split}_bridge_rank_p{position}"] = rank.cpu().numpy()
340
+ raw[split + "_attention"] = cache["attention_map"].cpu().numpy()
341
+ for recipient, _donor_position in [(3, 3), (6, 4)]:
342
+ for component in ["postresidual", "mlp_delta"]:
343
+ self_patch = {(0, component, recipient): cache[component][0, :, recipient]}
344
+ self_pred, self_prob = patched_generation(model, tokens, self_patch)
345
+ np.testing.assert_array_equal(self_pred, baseline_pred)
346
+ torch.testing.assert_close(self_prob, baseline_prob, rtol=1e-5, atol=2e-6)
347
+ for style, donor in select_donors(world, rows).items():
348
+ valid = donor["indices"] >= 0
349
+ ids = np.flatnonzero(valid)
350
+ if not len(ids):
351
+ continue
352
+ donor_rows = atoms[donor["indices"][valid]]
353
+ donor_tokens = torch.as_tensor(
354
+ [atomic_sentence(row)[:5] for row in donor_rows], device=device
355
+ )
356
+ _, donor_cache = traced_forward(model, donor_tokens)
357
+ expected = donor["tails"][valid]
358
+ expected_tensor = torch.as_tensor(expected, device=device)
359
+ premise = np.asarray(
360
+ [
361
+ atom_prediction["correct"][index_lookup[int(row[0]), int(row[1])]]
362
+ and atom_prediction["correct"][index_lookup[int(row[2]), int(row[3])]]
363
+ and atom_prediction["correct"][int(donor_index)]
364
+ and atom_prediction["correct"][index_lookup[int(donor_row[2]), int(row[3])]]
365
+ for row, donor_row, donor_index in zip(
366
+ rows[valid], donor_rows, donor["indices"][valid], strict=True
367
+ )
368
+ ]
369
+ )
370
+ raw[f"{split}_{style}_ids"] = ids
371
+ raw[f"{split}_{style}_donor_rows"] = donor_rows
372
+ raw[f"{split}_{style}_expected"] = expected
373
+ for recipient, donor_position in [(3, 3), (6, 4)]:
374
+ for component in ["postresidual", "mlp_delta"]:
375
+ patch = {
376
+ (0, component, recipient): donor_cache[component][0, :, donor_position]
377
+ }
378
+ pred, prob = patched_generation(model, tokens[valid], patch)
379
+ correct = (pred[:, 0] == expected) & (pred[:, 1] == 5) & (pred[:, 2] == 1)
380
+ base = baseline_pred[valid]
381
+ base_correct = (base[:, 0] == expected) & (base[:, 1] == 5) & (base[:, 2] == 1)
382
+ selected = torch.arange(len(ids), device=device)
383
+ new_probability = prob[selected, expected_tensor].cpu().numpy()
384
+ original_probability = (
385
+ baseline_prob[valid][selected, expected_tensor].cpu().numpy()
386
+ )
387
+ name = f"{split}_{style}_p{recipient}_{component}"
388
+ raw[name + "_generated"] = pred
389
+ raw[name + "_gold_probability"] = new_probability
390
+ raw[name + "_baseline_gold_probability"] = original_probability
391
+ record = {
392
+ "split": split,
393
+ "style": style,
394
+ "recipient_position": recipient,
395
+ "donor_position": donor_position,
396
+ "component": component,
397
+ "n": len(ids),
398
+ "pool_n": len(rows),
399
+ "coverage": float(valid.mean()),
400
+ "necessary_atoms_correct_n": int(premise.sum()),
401
+ "baseline_target_accuracy": float(base_correct.mean()),
402
+ "patched_target_accuracy": float(correct.mean()),
403
+ "target_accuracy_delta_pp": 100
404
+ * float((correct.astype(float) - base_correct).mean()),
405
+ "target_probability_delta": float(
406
+ (new_probability - original_probability).mean()
407
+ ),
408
+ "conditional_target_accuracy": float(correct[premise].mean())
409
+ if premise.any()
410
+ else None,
411
+ }
412
+ records.append(record)
413
+ out.mkdir(parents=True, exist_ok=False)
414
+ np.savez_compressed(out / "trace.npz", **raw)
415
+ result = {
416
+ "records": records,
417
+ "traced_forward_and_self_patch_passed": True,
418
+ "common_atomic": atom_metric,
419
+ }
420
+ write_json(out / "trace.json", result)
421
+ return result
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_reproduction.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Protocol replication of Wang et al.'s full-size two-hop grokking experiments.
2
+
3
+ The original GPT-2 vocabulary and configuration, answer/end-marker objective,
4
+ random graph, edge-level split, merged sampling and unique-depth initialization
5
+ are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are
6
+ explicit execution/numerical adaptations, checked against Hugging Face GPT-2.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import os
15
+ import time
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import functional as F
22
+ from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast
23
+
24
+ from .bios_model import ModelConfig, matmul_flops
25
+ from .grok_depth import EpochStream, GraphStep, utc, write_json
26
+
27
+ ROOT = Path("results/grokking-reproduction-v1")
28
+ ARTIFACTS = Path("docs/development-artifacts/grokking-reproduction-v1")
29
+ SOURCE_FILES = [
30
+ "src/llm_memory_editability/grokking_reproduction.py",
31
+ "scripts/run_grokking_reproduction.py",
32
+ "tests/test_grokking_reproduction.py",
33
+ "configs/grokking-reproduction-development-v1.json",
34
+ "docs/development-artifacts/grokking-reproduction-v1/design.md",
35
+ ]
36
+
37
+
38
+ def digest(path):
39
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
40
+
41
+
42
+ def model_digest(model):
43
+ h = hashlib.sha256()
44
+ for name, tensor in model.state_dict().items():
45
+ h.update(name.encode())
46
+ h.update(tensor.detach().cpu().contiguous().numpy().tobytes())
47
+ return h.hexdigest()
48
+
49
+
50
+ def build_graph(seed, entities=2000, relations=200, degree=20, holdout=0.005):
51
+ """Port the author's composition.ipynb; all tokens have shared graph roles.
52
+
53
+ The fixed permutation makes different phi supports nested while preserving
54
+ each support's uniform marginal distribution. Mixed OOD chains are retained
55
+ for diagnostic evaluation, never included in training.
56
+ """
57
+ rng = np.random.RandomState(seed)
58
+ atoms = np.empty((entities * degree, 3), dtype=np.int32)
59
+ for h in range(entities):
60
+ begin = h * degree
61
+ atoms[begin : begin + degree, 0] = h
62
+ atoms[begin : begin + degree, 1] = rng.choice(relations, degree, replace=False)
63
+ atoms[begin : begin + degree, 2] = rng.randint(entities, size=degree)
64
+ ood = np.zeros(len(atoms), dtype=bool)
65
+ ood[rng.choice(len(atoms), round(len(atoms) * 0.05), replace=False)] = True
66
+ first = np.repeat(np.arange(len(atoms)), degree)
67
+ second = atoms[first, 2] * degree + np.tile(np.arange(degree), len(atoms))
68
+ chains = np.column_stack(
69
+ [atoms[first, 0], atoms[first, 1], atoms[second, 1], atoms[second, 2]]
70
+ ).astype(np.int32)
71
+ kind = ood[first].astype(np.int8) * 2 + ood[second].astype(np.int8)
72
+ ii = np.flatnonzero(kind == 0)
73
+ held = rng.uniform(size=len(ii)) <= holdout
74
+ train_ids = ii[~held]
75
+ permutation = rng.permutation(len(train_ids))
76
+ return {
77
+ "atoms": atoms,
78
+ "ood": ood,
79
+ "chains": chains,
80
+ "first": first.astype(np.int32),
81
+ "second": second.astype(np.int32),
82
+ "kind": kind,
83
+ "train_order": train_ids[permutation].astype(np.int32),
84
+ "test_ii": ii[held].astype(np.int32),
85
+ }
86
+
87
+
88
+ def audit_graph(world, degree):
89
+ a, c = world["atoms"], world["chains"]
90
+ first, second = world["first"], world["second"]
91
+ assert np.array_equal(a[first, 2], a[second, 0])
92
+ assert np.array_equal(c[:, 0], a[first, 0])
93
+ assert np.array_equal(c[:, 1], a[first, 1])
94
+ assert np.array_equal(c[:, 2], a[second, 1])
95
+ assert np.array_equal(c[:, 3], a[second, 2])
96
+ assert len(np.unique(a[:, :2], axis=0)) == len(a)
97
+ assert np.all(np.bincount(a[:, 0]) == degree)
98
+ assert not np.intersect1d(world["train_order"], world["test_ii"]).size
99
+ assert np.all(world["kind"][world["train_order"]] == 0)
100
+ assert np.all(world["kind"][world["test_ii"]] == 0)
101
+
102
+
103
+ def prepare_data(config):
104
+ path = ROOT / "data"
105
+ path.mkdir(parents=True, exist_ok=True)
106
+ if (path / "complete.json").exists():
107
+ complete = json.loads((path / "complete.json").read_text())
108
+ assert complete["world"] == config["world"]
109
+ assert digest(path / "world.npz") == complete["world_sha256"]
110
+ return complete
111
+ world = build_graph(config["world"])
112
+ audit_graph(world, 20)
113
+ np.savez_compressed(path / "world.npz", **world)
114
+ rng = np.random.RandomState(config["evaluation_seed"])
115
+
116
+ def sample(indices):
117
+ return rng.choice(indices, min(3000, len(indices)), replace=False)
118
+
119
+ min_support = round(min(s["phi"] for s in config["runs"]) * (~world["ood"]).sum())
120
+ panels = {
121
+ "atomic_id": world["atoms"][sample(np.flatnonzero(~world["ood"]))],
122
+ "atomic_ood": world["atoms"][sample(np.flatnonzero(world["ood"]))],
123
+ "train_ii": world["chains"][sample(world["train_order"][:min_support])],
124
+ "test_ii": world["chains"][sample(world["test_ii"])],
125
+ "test_io": world["chains"][sample(np.flatnonzero(world["kind"] == 1))],
126
+ "test_oi": world["chains"][sample(np.flatnonzero(world["kind"] == 2))],
127
+ "test_oo": world["chains"][sample(np.flatnonzero(world["kind"] == 3))],
128
+ }
129
+ np.savez_compressed(path / "panels.npz", **panels)
130
+ tokenizer = GPT2TokenizerFast.from_pretrained(ROOT / "reference/gpt2", local_files_only=True)
131
+ base = len(tokenizer)
132
+ vocab = [f"<e_{i}>" for i in range(2000)] + [f"<r_{i}>" for i in range(200)]
133
+ vocab += ["<mask>", "<sep>", "<a>", "</a>", "<q>", "</q>"]
134
+ assert tokenizer.add_tokens(vocab) == len(vocab)
135
+ assert tokenizer.convert_tokens_to_ids(vocab) == list(range(base, base + len(vocab)))
136
+ tokenizer.pad_token = tokenizer.eos_token
137
+ tokenizer.save_pretrained(path / "tokenizer")
138
+ result = {
139
+ "world": config["world"],
140
+ "world_sha256": digest(path / "world.npz"),
141
+ "panels_sha256": digest(path / "panels.npz"),
142
+ "entities": 2000,
143
+ "relations": 200,
144
+ "degree": 20,
145
+ "atomic_id": int((~world["ood"]).sum()),
146
+ "atomic_ood": int(world["ood"].sum()),
147
+ "candidate_train_ii": len(world["train_order"]),
148
+ "full_test_ii": len(world["test_ii"]),
149
+ "panels": {k: len(v) for k, v in panels.items()},
150
+ "base_vocabulary": base,
151
+ "vocab_size": len(tokenizer),
152
+ "entity_offset": base,
153
+ "relation_offset": base + 2000,
154
+ "end_marker": tokenizer.convert_tokens_to_ids("</a>"),
155
+ "pad_token": tokenizer.pad_token_id,
156
+ "created_utc": utc(),
157
+ }
158
+ write_json(path / "complete.json", result)
159
+ write_json(ARTIFACTS / "data-audit.json", result)
160
+ return result
161
+
162
+
163
+ def encode_rows(rows, metadata):
164
+ """Only tail and </a> are targets; padding cannot influence earlier positions."""
165
+ rows = np.asarray(rows)
166
+ x = np.full((len(rows), 4), metadata["pad_token"], dtype=np.int64)
167
+ x[:, : rows.shape[1]] = rows
168
+ x[:, 0] += metadata["entity_offset"]
169
+ x[:, rows.shape[1] - 1] += metadata["entity_offset"]
170
+ x[:, 1 : rows.shape[1] - 1] += metadata["relation_offset"]
171
+ pos = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1))
172
+ labels = np.column_stack(
173
+ [rows[:, -1] + metadata["entity_offset"], np.full(len(rows), metadata["end_marker"])]
174
+ )
175
+ return x, pos, labels
176
+
177
+
178
+ def audit_support_roles(config):
179
+ world = dict(np.load(ROOT / "data/world.npz"))
180
+ panels = dict(np.load(ROOT / "data/panels.npz"))
181
+ atoms = world["atoms"]
182
+ lookup = np.full((2000, 200), -1, dtype=np.int32)
183
+ lookup[atoms[:, 0], atoms[:, 1]] = np.arange(len(atoms))
184
+ results = []
185
+ for phi in sorted({s["phi"] for s in config["runs"]}):
186
+ support = round(phi * (~world["ood"]).sum())
187
+ selected = world["train_order"][:support]
188
+ first = np.bincount(world["first"][selected], minlength=len(atoms))
189
+ second = np.bincount(world["second"][selected], minlength=len(atoms))
190
+ seen_pairs = np.zeros((2000, 2000), dtype=bool)
191
+ chains = world["chains"][selected]
192
+ seen_pairs[chains[:, 0], chains[:, 3]] = True
193
+ tasks = {}
194
+ for name, rows in panels.items():
195
+ if rows.shape[1] != 4:
196
+ continue
197
+ e1 = lookup[rows[:, 0], rows[:, 1]]
198
+ e2 = lookup[atoms[e1, 2], rows[:, 2]]
199
+ assert np.all(e1 >= 0) and np.all(e2 >= 0)
200
+ tasks[name] = {
201
+ "n": len(rows),
202
+ "first_fact_seen_in_first_role": float((first[e1] > 0).mean()),
203
+ "second_fact_seen_in_second_role": float((second[e2] > 0).mean()),
204
+ "both_seen_in_required_roles": float(((first[e1] > 0) & (second[e2] > 0)).mean()),
205
+ "head_tail_pair_seen_in_training": float(seen_pairs[rows[:, 0], rows[:, 3]].mean()),
206
+ }
207
+ results.append(
208
+ {
209
+ "phi": phi,
210
+ "support": support,
211
+ "composition_fraction": support / (len(atoms) + support),
212
+ "id_first_role_coverage": float((first[~world["ood"]] > 0).mean()),
213
+ "id_second_role_coverage": float((second[~world["ood"]] > 0).mean()),
214
+ "ood_first_role_count": int(first[world["ood"]].sum()),
215
+ "ood_second_role_count": int(second[world["ood"]].sum()),
216
+ "panels": tasks,
217
+ }
218
+ )
219
+ assert results[-1]["ood_first_role_count"] == results[-1]["ood_second_role_count"] == 0
220
+ write_json(ARTIFACTS / "support-role-audit.json", {"supports": results})
221
+ return results
222
+
223
+
224
+ class ReproductionGPT(nn.Module):
225
+ """Native HF initialization and modules, with equivalent supervised readout."""
226
+
227
+ def __init__(self, config, repeats=1):
228
+ super().__init__()
229
+ self.config, self.repeats = config, repeats
230
+ self.transformer = GPT2LMHeadModel(config).transformer
231
+
232
+ def forward(self, tokens, positions=None):
233
+ cfg, t = self.config, self.transformer
234
+ length = tokens.shape[1]
235
+ x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device))
236
+ x = F.dropout(x, cfg.embd_pdrop, self.training)
237
+ for _ in range(self.repeats):
238
+ for block in t.h:
239
+ z = block.ln_1(x)
240
+ q, k, v = block.attn.c_attn(z).split(cfg.n_embd, dim=2)
241
+ shape = (len(tokens), length, cfg.n_head, cfg.n_embd // cfg.n_head)
242
+ q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v))
243
+ y = F.scaled_dot_product_attention(
244
+ q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0
245
+ )
246
+ y = block.attn.c_proj(y.transpose(1, 2).reshape(len(tokens), length, cfg.n_embd))
247
+ x = x + F.dropout(y, cfg.resid_pdrop, self.training)
248
+ x = x + block.mlp(block.ln_2(x))
249
+ x = t.ln_f(x)
250
+ if positions is not None:
251
+ x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
252
+ return F.linear(x, t.wte.weight)
253
+
254
+
255
+ def construct(spec, metadata, device):
256
+ torch.manual_seed(spec["initialization"])
257
+ cfg = GPT2Config.from_pretrained(ROOT / "reference/gpt2", local_files_only=True)
258
+ cfg.vocab_size = metadata["vocab_size"]
259
+ cfg.n_layer = spec["unique_layers"]
260
+ cfg.use_cache = False
261
+ return ReproductionGPT(cfg, spec["repeats"]).to(device)
262
+
263
+
264
+ def optimizer_for(model, lr, decay):
265
+ params = list(model.named_parameters())
266
+ return torch.optim.AdamW(
267
+ [
268
+ {
269
+ "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])],
270
+ "weight_decay": decay,
271
+ },
272
+ {
273
+ "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])],
274
+ "weight_decay": 0.0,
275
+ },
276
+ ],
277
+ lr=lr,
278
+ betas=(0.9, 0.999),
279
+ eps=1e-8,
280
+ fused=True,
281
+ capturable=True,
282
+ )
283
+
284
+
285
+ class ReproductionStep(GraphStep):
286
+ def eager(self):
287
+ self.optimizer.zero_grad(set_to_none=False)
288
+ x, positions, labels = (part[self.index] for part in self.table)
289
+ with torch.autocast("cuda", dtype=torch.bfloat16):
290
+ logits = self.model(x, positions)
291
+ loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten())
292
+ loss.backward()
293
+ norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
294
+ self.optimizer.step()
295
+ return loss, norm
296
+
297
+
298
+ class MergedBatchStream(EpochStream):
299
+ """Match DataLoader's final partial batch using loss-masked graph padding."""
300
+
301
+ def batch(self, batch_size):
302
+ if not len(self.remaining):
303
+ self.remaining = self.rng.permutation(self.size)
304
+ count = min(batch_size, len(self.remaining))
305
+ result = np.full(batch_size, self.size, dtype=np.int64)
306
+ result[:count] = self.remaining[:count]
307
+ self.remaining = self.remaining[count:]
308
+ return result, count
309
+
310
+
311
+ @torch.no_grad()
312
+ def evaluate_rows(model, rows, metadata, device, batch_size=256):
313
+ model.eval()
314
+ packed = encode_rows(rows, metadata)
315
+ answers, stops, losses = [], [], []
316
+ for start in range(0, len(rows), batch_size):
317
+ x, pos, labels = [
318
+ torch.as_tensor(p[start : start + batch_size], device=device) for p in packed
319
+ ]
320
+ with torch.autocast("cuda", dtype=torch.bfloat16):
321
+ logits = model(x, pos)
322
+ nll = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none")
323
+ answer = logits[:, 0].argmax(-1)
324
+ x[torch.arange(len(x), device=device), pos[:, 1]] = answer
325
+ stop = model(x, pos)[:, 1].argmax(-1)
326
+ answers.append(answer.cpu().numpy())
327
+ stops.append(stop.cpu().numpy())
328
+ losses.append(nll.view(-1, 2).float().cpu().numpy())
329
+ model.train()
330
+ answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses)
331
+ correct = answer == rows[:, -1] + metadata["entity_offset"]
332
+ return {
333
+ "n": len(rows),
334
+ "answer_accuracy": float(correct.mean()),
335
+ "accuracy": float((correct & (stop == metadata["end_marker"])).mean()),
336
+ "answer_nll": float(nll[:, 0].mean()),
337
+ "nll": float(nll.mean()),
338
+ }, {"answer": answer, "stop": stop, "nll": nll, "rows": rows}
339
+
340
+
341
+ def learning_rate(spec, step):
342
+ # HF's warmup schedule starts the first optimizer update at zero LR.
343
+ return spec["lr"] * min((step - 1) / spec["warmup"], 1.0)
344
+
345
+
346
+ def save_checkpoint(path, model, optimizer, stream, counts, step, spec, training_seconds):
347
+ tmp = path.with_suffix(".tmp")
348
+ torch.save(
349
+ {
350
+ "model": model.state_dict(),
351
+ "optimizer": optimizer.state_dict(),
352
+ "stream": stream.state_dict(),
353
+ "counts": counts,
354
+ "step": step,
355
+ "spec": spec,
356
+ "cpu_rng": torch.get_rng_state(),
357
+ "cuda_rng": torch.cuda.get_rng_state(),
358
+ "training_seconds": training_seconds,
359
+ },
360
+ tmp,
361
+ )
362
+ tmp.replace(path)
363
+
364
+
365
+ def train_run(config, spec, gpu):
366
+ torch.set_num_threads(4)
367
+ if torch.get_num_interop_threads() != 1:
368
+ torch.set_num_interop_threads(1)
369
+ torch.cuda.set_device(gpu)
370
+ torch.backends.cuda.matmul.allow_tf32 = True
371
+ device = torch.device(f"cuda:{gpu}")
372
+ out = ROOT / "development" / spec["name"]
373
+ out.mkdir(parents=True, exist_ok=True)
374
+ if (out / "complete.json").exists():
375
+ return
376
+ metadata = json.loads((ROOT / "data/complete.json").read_text())
377
+ assert digest(ROOT / "data/world.npz") == metadata["world_sha256"]
378
+ assert digest(ROOT / "data/panels.npz") == metadata["panels_sha256"]
379
+ world = dict(np.load(ROOT / "data/world.npz"))
380
+ support = round(spec["phi"] * metadata["atomic_id"])
381
+ selected = world["train_order"][:support]
382
+ assert len(selected) == support
383
+ atomic = encode_rows(world["atoms"], metadata)
384
+ composite = encode_rows(world["chains"][selected], metadata)
385
+ padding = (
386
+ np.full((1, 4), metadata["pad_token"], dtype=np.int64),
387
+ np.array([[2, 3]], dtype=np.int64),
388
+ np.array([[-100, -100]], dtype=np.int64),
389
+ )
390
+ table = tuple(
391
+ torch.as_tensor(np.concatenate([a, b, p]), device=device)
392
+ for a, b, p in zip(atomic, composite, padding, strict=True)
393
+ )
394
+ del atomic, composite
395
+ model = construct(spec, metadata, device)
396
+ initial_hash = model_digest(model)
397
+ lr = torch.tensor(0.0, device=device)
398
+ optimizer = optimizer_for(model, lr, spec["weight_decay"])
399
+ stream = MergedBatchStream(len(table[0]) - 1, spec["stream_seed"])
400
+ counts = np.zeros(len(table[0]) - 1, dtype=np.int64)
401
+ step, training_seconds = 0, 0.0
402
+ latest = out / "latest.pt"
403
+ rng = None
404
+ if latest.exists():
405
+ saved = torch.load(latest, map_location=device, weights_only=False)
406
+ assert saved["spec"] == spec
407
+ model.load_state_dict(saved["model"])
408
+ optimizer.load_state_dict(saved["optimizer"])
409
+ # load_state_dict can replace group LR objects; refill the object the optimizer uses.
410
+ lr = optimizer.param_groups[0]["lr"]
411
+ for group in optimizer.param_groups:
412
+ group["lr"] = lr
413
+ stream.load_state_dict(saved["stream"])
414
+ counts, step = saved["counts"], saved["step"]
415
+ training_seconds = saved["training_seconds"]
416
+ rng = (saved["cpu_rng"].cpu(), saved["cuda_rng"].cpu())
417
+ del saved
418
+ if rng is not None:
419
+ torch.set_rng_state(rng[0])
420
+ torch.cuda.set_rng_state(rng[1])
421
+ model.train()
422
+ graph = ReproductionStep(model, optimizer, table, spec["batch_size"])
423
+ panels = dict(np.load(ROOT / "data/panels.npz"))
424
+ learning_path = out / "learning.json"
425
+ history = json.loads(learning_path.read_text()) if learning_path.exists() else []
426
+ history = [r for r in history if r["step"] <= step]
427
+ started = time.perf_counter()
428
+ parameters = sum(p.numel() for p in model.parameters())
429
+ flop_step = matmul_flops(
430
+ ModelConfig(
431
+ metadata["vocab_size"],
432
+ model.config.n_embd,
433
+ model.config.n_layer * model.repeats,
434
+ model.config.n_head,
435
+ 1024,
436
+ ),
437
+ spec["batch_size"],
438
+ sequence=4,
439
+ output_positions=2,
440
+ )
441
+ write_json(
442
+ out / "run.json",
443
+ {
444
+ "spec": spec,
445
+ "world_sha256": metadata["world_sha256"],
446
+ "initial_model_sha256": initial_hash,
447
+ "parameters": parameters,
448
+ "atomic_examples": len(world["atoms"]),
449
+ "composition_examples": support,
450
+ "vocab_size": metadata["vocab_size"],
451
+ "gpu": gpu,
452
+ "gpu_name": torch.cuda.get_device_name(gpu),
453
+ "started_utc": utc(),
454
+ "dtype": "bf16 AMP with float32 parameters/Adam state",
455
+ "pid": os.getpid(),
456
+ "resumed_step": step,
457
+ },
458
+ )
459
+
460
+ def measure():
461
+ metrics = {}
462
+ for name, panel in panels.items():
463
+ metrics[name], pred = evaluate_rows(model, panel, metadata, device)
464
+ np.savez_compressed(out / f"predictions-{step:07d}-{name}.npz", **pred)
465
+ record = {
466
+ "step": step,
467
+ "metrics": metrics,
468
+ "training_seconds": training_seconds,
469
+ "wall_seconds": time.perf_counter() - started,
470
+ "created_utc": utc(),
471
+ "examples": int(counts.sum()),
472
+ "supervised_tokens": int(counts.sum()) * 2,
473
+ "executed_input_tokens": step * spec["batch_size"] * 4,
474
+ "estimated_matmul_training_flops": step * flop_step,
475
+ "composition_epochs": float(counts[len(world["atoms"]) :].sum() / support),
476
+ "atomic_epochs": float(counts[: len(world["atoms"])].sum() / len(world["atoms"])),
477
+ }
478
+ history.append(record)
479
+ write_json(learning_path, history)
480
+ write_json(
481
+ out / "status.json",
482
+ {
483
+ "state": "running",
484
+ "step": step,
485
+ "budget": spec["steps"],
486
+ "training_seconds": training_seconds,
487
+ "train_ii": metrics["train_ii"]["accuracy"],
488
+ "test_ii": metrics["test_ii"]["accuracy"],
489
+ "test_oo": metrics["test_oo"]["accuracy"],
490
+ "updated_utc": utc(),
491
+ },
492
+ )
493
+ print(
494
+ json.dumps(
495
+ {
496
+ "name": spec["name"],
497
+ "step": step,
498
+ "train": metrics["train_ii"]["accuracy"],
499
+ "id": metrics["test_ii"]["accuracy"],
500
+ "oo": metrics["test_oo"]["accuracy"],
501
+ }
502
+ ),
503
+ flush=True,
504
+ )
505
+
506
+ def checkpoint():
507
+ save_checkpoint(latest, model, optimizer, stream, counts, step, spec, training_seconds)
508
+ retained = out / f"checkpoint-{step:07d}.pt"
509
+ torch.save({"model": model.state_dict(), "spec": spec, "step": step}, retained)
510
+ np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts, selected=selected)
511
+
512
+ if not history or history[-1]["step"] != step:
513
+ measure()
514
+ if step == 0 and 0 in config["checkpoint_nodes"]:
515
+ checkpoint()
516
+ for end in [n for n in config["evaluation_nodes"] if n > step]:
517
+ torch.cuda.synchronize()
518
+ segment = time.perf_counter()
519
+ while step < end:
520
+ n = min(128, end - step)
521
+ indices = np.stack([stream.batch(spec["batch_size"])[0] for _ in range(n)])
522
+ counts += np.bincount(indices.ravel(), minlength=len(counts) + 1)[: len(counts)]
523
+ indices = torch.as_tensor(indices, device=device)
524
+ for i in range(n):
525
+ lr.fill_(learning_rate(spec, step + i + 1))
526
+ loss = graph(indices[i])
527
+ step += n
528
+ torch.cuda.synchronize()
529
+ training_seconds += time.perf_counter() - segment
530
+ loss_value = float(loss)
531
+ if not math.isfinite(loss_value) or not math.isfinite(float(graph.grad_norm)):
532
+ raise FloatingPointError(f"Nonfinite loss/gradient at {step}")
533
+ measure()
534
+ if step in config["checkpoint_nodes"]:
535
+ checkpoint()
536
+ assert step == spec["steps"]
537
+ epoch_steps = math.ceil(len(counts) / spec["batch_size"])
538
+ full_epochs, remainder = divmod(step, epoch_steps)
539
+ expected_examples = full_epochs * len(counts) + remainder * spec["batch_size"]
540
+ assert counts.sum() == expected_examples
541
+ assert counts.max() - counts.min() <= 1
542
+ # Full endpoint evaluation complements the original fixed 3k training panels.
543
+ full = {}
544
+ for name, data in {
545
+ "atomic_all": world["atoms"],
546
+ "train_ii_all": world["chains"][selected],
547
+ }.items():
548
+ full[name], pred = evaluate_rows(model, data, metadata, device)
549
+ np.savez_compressed(out / f"endpoint-{name}.npz", **pred)
550
+ final = {
551
+ "state": "complete",
552
+ "step": step,
553
+ "full_endpoint": full,
554
+ "parameters": parameters,
555
+ "training_seconds": training_seconds,
556
+ "wall_seconds": time.perf_counter() - started,
557
+ "estimated_matmul_training_flops": step * flop_step,
558
+ "completed_utc": utc(),
559
+ "final_checkpoint_sha256": digest(out / f"checkpoint-{step:07d}.pt"),
560
+ "model_sha256": model_digest(model),
561
+ }
562
+ write_json(out / "complete.json", final)
563
+ write_json(out / "status.json", final)
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_data.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CounterFact true-label data, explicit audit decisions and indivisible subject pools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import unicodedata
8
+ from collections import Counter, defaultdict
9
+
10
+ import numpy as np
11
+
12
+ from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, sha256, write_json
13
+
14
+ TEMPLATE = "Complete the statement with the missing answer only.\nStatement: {}\nAnswer:"
15
+
16
+
17
+ def normalize(text):
18
+ return " ".join(unicodedata.normalize("NFKC", text).split()).casefold()
19
+
20
+
21
+ def normalize_answer(text):
22
+ text = normalize(text)
23
+ while text and unicodedata.category(text[-1]).startswith("P"):
24
+ text = text[:-1].rstrip()
25
+ return text
26
+
27
+
28
+ def score_answer(prediction, aliases):
29
+ lines = [x.strip() for x in prediction.splitlines() if x.strip()]
30
+ first = lines[0] if lines else ""
31
+ return int(normalize_answer(first) in {normalize_answer(x) for x in aliases})
32
+
33
+
34
+ def encode_answer(tokenizer, prompt, answer):
35
+ """Tokenize the complete string once; offset overlap includes leading answer space."""
36
+ suffix = " " + answer
37
+ text = prompt + suffix
38
+ encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
39
+ ids, offsets = encoded["input_ids"], encoded["offset_mapping"]
40
+ start = len(prompt)
41
+ mask = [int(end > start) for begin, end in offsets]
42
+ if any(begin < start < end for begin, end in offsets):
43
+ raise ValueError("A token straddles the prompt/answer boundary")
44
+ answer_start = mask.index(1)
45
+ if ids[:answer_start] != tokenizer(prompt, add_special_tokens=False)["input_ids"]:
46
+ raise ValueError("Prompt tokenization changes at the answer boundary")
47
+ assert not any(mask[:answer_start]) and all(mask[answer_start:])
48
+ return {
49
+ "input_ids": ids + [tokenizer.eos_token_id],
50
+ "loss_mask": mask + [1],
51
+ "answer_start": answer_start,
52
+ "answer_tokens": sum(mask),
53
+ "prompt_tokens": answer_start,
54
+ }
55
+
56
+
57
+ def stable_hash(text):
58
+ return hashlib.sha256(text.encode()).hexdigest()
59
+
60
+
61
+ def clean_candidates(tokenizer):
62
+ cfg = config()["data"]
63
+ raw_path = DATA / "source/counterfact.json"
64
+ raw = read_json(raw_path)
65
+ audit, candidates, seen = [], [], {}
66
+ conflicting = set()
67
+ # Near-identical punctuation/accent variants are conservatively quarantined;
68
+ # normalized identical subjects already share a group.
69
+ subjects = defaultdict(set)
70
+ for row in raw:
71
+ name = normalize(row["requested_rewrite"]["subject"])
72
+ key = "".join(c for c in unicodedata.normalize("NFKD", name) if c.isalnum())
73
+ subjects[key].add(name)
74
+ ambiguous = set().union(*(v for v in subjects.values() if len(v) > 1))
75
+ for row in raw:
76
+ r = row["requested_rewrite"]
77
+ if r["relation_id"] not in cfg["relations"]:
78
+ continue
79
+ subject = " ".join(unicodedata.normalize("NFKC", r["subject"]).split())
80
+ group = normalize(subject)
81
+ answer = r["target_true"]["str"].strip()
82
+ views = [r["prompt"].format(r["subject"])] + row["paraphrase_prompts"][:2]
83
+ views = [" ".join(unicodedata.normalize("NFKC", p).split()) for p in views]
84
+ reasons = []
85
+ decision = "include"
86
+ if len(views) != 3 or len(set(map(normalize, views))) != 3:
87
+ reasons.append("missing_or_duplicate_views")
88
+ if any(
89
+ re.search(r"(?<!\w)" + re.escape(normalize(answer)) + r"(?!\w)", normalize(p))
90
+ for p in views
91
+ ):
92
+ reasons.append("answer_leakage_in_prompt_or_subject")
93
+ if any(normalize(subject) not in normalize(p) for p in views):
94
+ reasons.append("subject_missing_from_view")
95
+ if group in ambiguous:
96
+ reasons.append("possible_subject_alias")
97
+ decision = "review"
98
+ # Some source paraphrases ask nationality, not native language.
99
+ if r["relation_id"] == "P103" and any(p.endswith(", a native") for p in views):
100
+ reasons.append("native_is_ambiguous_between_language_and_origin")
101
+ decision = "review"
102
+ # Manufacturer names truncated to a country or a non-unique first word.
103
+ if r["relation_id"] in {"P176", "P178"} and answer in {"Iran", "Douglas", "Square"}:
104
+ reasons.append("source_answer_name_requires_entity_review")
105
+ decision = "review"
106
+ encoded = []
107
+ try:
108
+ encoded = [encode_answer(tokenizer, TEMPLATE.format(p), answer) for p in views]
109
+ if any(x["prompt_tokens"] > cfg["prompt_max_tokens"] for x in encoded):
110
+ reasons.append("prompt_over_limit")
111
+ if any(x["answer_tokens"] > cfg["answer_max_tokens"] for x in encoded):
112
+ reasons.append("answer_over_limit")
113
+ except ValueError as e:
114
+ reasons.append(str(e))
115
+ key = (group, r["relation_id"])
116
+ if key in seen:
117
+ previous = seen[key]
118
+ if previous["target_id"] == r["target_true"]["id"]:
119
+ previous["source_ids"].append(row["case_id"])
120
+ reasons.append("merged_subject_relation_duplicate")
121
+ else:
122
+ reasons.append("conflicting_subject_relation_targets")
123
+ decision = "review"
124
+ conflicting.add(key)
125
+ if reasons and decision == "include":
126
+ decision = "exclude"
127
+ record = {
128
+ "case_id": row["case_id"],
129
+ "source_ids": [row["case_id"]],
130
+ "subject": subject,
131
+ "subject_group": group,
132
+ "relation_id": r["relation_id"],
133
+ "target_id": r["target_true"]["id"],
134
+ "answer": answer,
135
+ "target_new_source_only": r["target_new"],
136
+ "views": views,
137
+ "encoded": encoded,
138
+ }
139
+ audit.append(
140
+ {
141
+ "case_id": row["case_id"],
142
+ "decision": decision,
143
+ "reasons": reasons,
144
+ "audit_type": "programmatic",
145
+ "subject_group": group,
146
+ }
147
+ )
148
+ if decision == "include":
149
+ candidates.append(record)
150
+ seen[key] = record
151
+ # Conflicting labels disqualify every side of a conflict, including the first row.
152
+ conflict_ids = {
153
+ r["case_id"] for r in candidates if (r["subject_group"], r["relation_id"]) in conflicting
154
+ }
155
+ for entry in audit:
156
+ if entry["case_id"] in conflict_ids:
157
+ entry["decision"] = "review"
158
+ entry["reasons"].append("conflicting_subject_relation_targets")
159
+ candidates = [r for r in candidates if r["case_id"] not in conflict_ids]
160
+ prompt_owners = defaultdict(set)
161
+ for record in candidates:
162
+ for prompt in record["views"]:
163
+ prompt_owners[normalize(prompt)].add(record["subject_group"])
164
+ collision_ids = {
165
+ r["case_id"]
166
+ for r in candidates
167
+ if any(len(prompt_owners[normalize(p)]) > 1 for p in r["views"])
168
+ }
169
+ for entry in audit:
170
+ if entry["case_id"] in collision_ids:
171
+ entry["decision"] = "review"
172
+ entry["reasons"].append("cross_subject_prompt_collision")
173
+ candidates = [r for r in candidates if r["case_id"] not in collision_ids]
174
+ # Each pool gets a disjoint candidate reserve before any baseline outcome is observed.
175
+ # Extra keep reserve accounts for its required pre-existing exact generation success.
176
+ pool_weights = {k: n * (3 if k.endswith("keep") else 1) for k, n in cfg["pools"].items()}
177
+ total_weight = sum(pool_weights.values())
178
+ by_subject = defaultdict(list)
179
+ for r in candidates:
180
+ by_subject[r["subject_group"]].append(r)
181
+ stratified = defaultdict(list)
182
+ for group, rows in by_subject.items():
183
+ stratified[min(r["relation_id"] for r in rows)].append(group)
184
+ rng = np.random.default_rng(cfg["split_seed"])
185
+ for _relation, groups in sorted(stratified.items()):
186
+ groups.sort(key=stable_hash)
187
+ rng.shuffle(groups)
188
+ cumulative = 0.0
189
+ start = 0
190
+ for pool, weight in pool_weights.items():
191
+ cumulative += weight / total_weight
192
+ end = round(cumulative * len(groups))
193
+ for group in groups[start:end]:
194
+ for record in by_subject[group]:
195
+ record["candidate_pool"] = pool
196
+ start = end
197
+ write_json(DATA / "candidates.json", candidates)
198
+ write_json(ARTIFACTS / "programmatic-audit.json", audit)
199
+ write_json(
200
+ ARTIFACTS / "subject-alias-audit.json",
201
+ {
202
+ "method": "NFKC/casefold grouping; punctuation/accent variants quarantined",
203
+ "limitations": "No claim of exhaustive real-world entity resolution",
204
+ "review_groups": [sorted(v) for v in subjects.values() if len(v) > 1],
205
+ },
206
+ )
207
+ write_json(
208
+ ARTIFACTS / "preparation.json",
209
+ {
210
+ "time": now(),
211
+ "raw_count": len(raw),
212
+ "source_sha256": sha256(raw_path),
213
+ "candidate_count": len(candidates),
214
+ "decisions": dict(Counter(x["decision"] for x in audit)),
215
+ "reasons": dict(Counter(y for x in audit for y in x["reasons"])),
216
+ "candidate_pools": dict(Counter(x["candidate_pool"] for x in candidates)),
217
+ "candidate_sha256": sha256(DATA / "candidates.json"),
218
+ "status": "awaiting_individual_semantic_audit_and_baseline",
219
+ "source_license": (
220
+ "CounterFact source snapshot; upstream ROME repository MIT; "
221
+ "dataset-specific license not asserted"
222
+ ),
223
+ },
224
+ )
225
+ return candidates
226
+
227
+
228
+ def balanced_order(records, seed):
229
+ rng = np.random.default_rng(seed)
230
+ groups = defaultdict(list)
231
+ for record in sorted(records, key=lambda r: r["case_id"]):
232
+ groups[record["relation_id"]].append(record)
233
+ for items in groups.values():
234
+ rng.shuffle(items)
235
+ result = []
236
+ while any(groups.values()):
237
+ for relation in sorted(groups):
238
+ if groups[relation]:
239
+ result.append(groups[relation].pop())
240
+ return result
241
+
242
+
243
+ def semantic_audit():
244
+ """Apply explicitly reviewed predicate rules; retain per-row evidence and limitations.
245
+
246
+ This is a reproducible semantic rule audit, not a claim that a human or another
247
+ model independently reviewed every source fact. Benchmark truth is assumed.
248
+ """
249
+ candidates = read_json(DATA / "candidates.json")
250
+ result = []
251
+ for record in candidates:
252
+ issues, evidence = [], []
253
+ subject = normalize(record["subject"])
254
+ relation = record["relation_id"]
255
+ for view in record["views"]:
256
+ text = normalize(view)
257
+ start = text.rfind(subject)
258
+ suffix = text[start + len(subject) :].strip()
259
+ prefix = text[:start]
260
+ evidence.append({"predicate_suffix": suffix, "relation_prefix": prefix[-64:]})
261
+ if relation == "P19" and suffix != "was born in":
262
+ issues.append("origin_or_native_place_does_not_uniquely_mean_birthplace")
263
+ if relation == "P103" and (suffix in {"spoke the language", ", speaker of"}):
264
+ issues.append("spoken_language_does_not_uniquely_mean_mother_tongue")
265
+ if (
266
+ relation == "P103"
267
+ and suffix == "is"
268
+ and not any(
269
+ prefix.endswith(p) for p in ["the mother tongue of ", "the native language of "]
270
+ )
271
+ ):
272
+ issues.append("missing_native_language_relation")
273
+ if relation == "P176" and "developed by" in suffix:
274
+ issues.append("developer_is_not_necessarily_manufacturer")
275
+ if relation == "P178" and "manufactured by" in suffix:
276
+ issues.append("manufacturer_is_not_necessarily_developer")
277
+ if (
278
+ relation in {"P364", "P407"}
279
+ and suffix in {"is", "was"}
280
+ and not any(
281
+ prefix.endswith(p) for p in ["the language of ", "the original language of "]
282
+ )
283
+ ):
284
+ issues.append("missing_language_relation")
285
+ result.append(
286
+ {
287
+ "case_id": record["case_id"],
288
+ "decision": "review" if issues else "include",
289
+ "reasons": sorted(set(issues)),
290
+ "view_evidence": evidence,
291
+ "audit_type": "model_authored_semantic_rules_applied_programmatically",
292
+ "truth_status": "CounterFact original label; no independent fact verification",
293
+ }
294
+ )
295
+ write_json(ARTIFACTS / "semantic-audit.json", result)
296
+ write_json(
297
+ ARTIFACTS / "semantic-audit-method.json",
298
+ {
299
+ "time": now(),
300
+ "status": "conservative_template_semantics_audit",
301
+ "decisions": dict(Counter(r["decision"] for r in result)),
302
+ "limitations": [
303
+ "Real-world truths and all entity aliases are not independently verified",
304
+ "Creator/product/origin formulations use source benchmark semantics",
305
+ "Model-authored rule audit; independent human review not performed",
306
+ ],
307
+ "primary_subset": "Only all-three-view records passing these conservative rules",
308
+ "review_pool": "Excluded from all fitting and evaluation; never auto-promoted",
309
+ },
310
+ )
311
+ return result
312
+
313
+
314
+ def lock_data():
315
+ """No training may consume unaudited rows or an outcome-adapted subject split."""
316
+ cfg = config()["data"]
317
+ candidates = read_json(DATA / "candidates.json")
318
+ semantic = {r["case_id"]: r for r in read_json(ARTIFACTS / "semantic-audit.json")}
319
+ baseline = {r["case_id"]: r for r in read_json(DATA / "baseline.json")}
320
+ pools, coverage = {}, {}
321
+ for name, count in cfg["pools"].items():
322
+ available = [
323
+ r
324
+ for r in candidates
325
+ if r["candidate_pool"] == name
326
+ and semantic.get(r["case_id"], {}).get("decision") == "include"
327
+ and r["case_id"] in baseline
328
+ ]
329
+ if name.endswith("keep"):
330
+ available = [r for r in available if baseline[r["case_id"]]["views"][0]["answer_em"]]
331
+ ordered = balanced_order(available, cfg["split_seed"])
332
+ if name.startswith(("B_", "C_")):
333
+
334
+ def needs_learning(r):
335
+ v = baseline[r["case_id"]]["views"]
336
+ return not v[0]["answer_em"] and not all(x["answer_em"] for x in v[1:])
337
+
338
+ ordered = [r for r in ordered if needs_learning(r)] + [
339
+ r for r in ordered if not needs_learning(r)
340
+ ]
341
+ unit = cfg["episode_size"].get(name, 8)
342
+ actual = min(count, len(ordered) // unit * unit)
343
+ if actual < unit:
344
+ raise ValueError(f"{name} has fewer than one complete batch/episode: {len(ordered)}")
345
+ pools[name] = ordered[:actual]
346
+ coverage[name] = {
347
+ "planned": count,
348
+ "available": len(ordered),
349
+ "actual": actual,
350
+ "relations": dict(Counter(r["relation_id"] for r in ordered[:actual])),
351
+ }
352
+ group_sets = {k: {r["subject_group"] for r in rows} for k, rows in pools.items()}
353
+ names = list(pools)
354
+ for i, a in enumerate(names):
355
+ for b in names[i + 1 :]:
356
+ assert not group_sets[a] & group_sets[b], (a, b)
357
+ aliases = defaultdict(set)
358
+ for rows in pools.values():
359
+ for r in rows:
360
+ aliases[r["target_id"]].add(r["answer"])
361
+ for rows in pools.values():
362
+ for r in rows:
363
+ r["aliases"] = sorted(aliases[r["target_id"]])
364
+ r["baseline"] = baseline[r["case_id"]]
365
+ episodes = {
366
+ name: [
367
+ [r["case_id"] for r in rows[i : i + cfg["episode_size"][name]]]
368
+ for i in range(0, len(rows), cfg["episode_size"][name])
369
+ ]
370
+ for name, rows in pools.items()
371
+ if name in cfg["episode_size"]
372
+ }
373
+ write_json(DATA / "pools.json", pools)
374
+ write_json(DATA / "episodes.json", episodes)
375
+ write_json(
376
+ ARTIFACTS / "data-lock.json",
377
+ {
378
+ "time": now(),
379
+ "coverage": coverage,
380
+ "subject_disjoint": True,
381
+ "files": {
382
+ p: sha256(DATA / p)
383
+ for p in [
384
+ "candidates.json",
385
+ "pools.json",
386
+ "episodes.json",
387
+ "baseline.json",
388
+ "text.json",
389
+ ]
390
+ },
391
+ "semantic_audit_sha256": sha256(ARTIFACTS / "semantic-audit.json"),
392
+ "revision": "Full-episode coverage reduction before model learning, where needed",
393
+ "status": "locked",
394
+ },
395
+ )
396
+ return coverage
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_followup.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-content worlds and conservative full-entity answer parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import unicodedata
8
+ from collections import defaultdict
9
+
10
+ import numpy as np
11
+
12
+ from .hebbian_future import ROOT, chain_world
13
+
14
+ CONFIG = ROOT / "configs/hebbian-future-v2.json"
15
+ ART = ROOT / "docs/development-artifacts/hebbian-future-v2"
16
+ DATA = ROOT / "data/hebbian-future-v2"
17
+ RESULTS = ROOT / "results/hebbian-future-v2"
18
+
19
+
20
+ def stable(value):
21
+ return hashlib.sha256(str(value).encode()).hexdigest()
22
+
23
+
24
+ def fixed_world(world, rho, cfg):
25
+ """Change only nonfocal home values as rho changes; focal wrong values stay fixed."""
26
+ w = chain_world(world, rho, cfg)
27
+ rng = np.random.default_rng(world + 918273)
28
+ people = rng.permutation(cfg["people"]).reshape(cfg["organizations"], 8)
29
+ hq = rng.permutation(np.arange(cfg["organizations"]) % cfg["cities"])
30
+ city_order = rng.permutation(cfg["cities"])
31
+ matches = int(rho * 4)
32
+ for group, persons in enumerate(people):
33
+ for split in range(2):
34
+ selected = persons[split * 4 : split * 4 + 4]
35
+ # Offset of slot j is j at EVERY rho until made coherent. Slot 3
36
+ # is always the same competing city, in both train and held-out.
37
+ offsets = np.arange(4)
38
+ offsets[:matches] = 0
39
+ w["home"][selected] = city_order[(hq[group] + offsets) % 4]
40
+ w["home_y"] = w["city_start"] + w["home"]
41
+ return w
42
+
43
+
44
+ def normalize(text):
45
+ return " ".join(unicodedata.normalize("NFKC", text).casefold().split())
46
+
47
+
48
+ def inventory_from_facts(facts):
49
+ inventory = defaultdict(dict)
50
+ for fact in facts:
51
+ values = inventory[fact["relation_id"]]
52
+ item = values.setdefault(fact["target_id"], {"label": fact["answer"], "aliases": []})
53
+ item["aliases"] = sorted(set(item["aliases"] + fact.get("aliases", []) + [fact["answer"]]))
54
+ return dict(inventory)
55
+
56
+
57
+ def parse_entity(text, inventory):
58
+ """Read a leading complete alias, abstaining on collisions/negation/lists.
59
+
60
+ Plain completion makes a leading answer meaningful. The parser does not
61
+ convert every nonmatch into factual error. No model-assisted grading.
62
+ """
63
+ text = normalize(text).lstrip(" \"'`“”‘’([{:")
64
+ if not text:
65
+ return {"status": "unrecognized", "entity": None}
66
+ if re.match(r"(?:not|no|neither|unknown|i don't|i do not)\b", text):
67
+ return {"status": "unrecognized", "entity": None}
68
+ matches = []
69
+ for entity, item in inventory.items():
70
+ for alias in item["aliases"]:
71
+ a = normalize(alias)
72
+ if text.startswith(a) and (len(text) == len(a) or not text[len(a)].isalnum()):
73
+ matches.append((len(a), entity))
74
+ if not matches:
75
+ return {"status": "unrecognized", "entity": None}
76
+ length = max(n for n, _ in matches)
77
+ entities = {entity for n, entity in matches if n == length}
78
+ if len(entities) != 1:
79
+ return {"status": "ambiguous", "entity": None}
80
+ suffix = text[length:].lstrip()
81
+ if re.match(r"(?:and|or|/|,?\s*not)\b", suffix):
82
+ return {"status": "ambiguous", "entity": None}
83
+ return {"status": "recognized", "entity": next(iter(entities))}
84
+
85
+
86
+ def candidate_set(fact, inventory, seed):
87
+ items = inventory[fact["relation_id"]]
88
+ own_aliases = {normalize(a) for a in items[fact["target_id"]]["aliases"]}
89
+ ordered = sorted(items, key=lambda x: stable(f"{seed}:{fact['case_id']}:{x}"))
90
+ selected = [fact["target_id"]]
91
+ aliases = set(own_aliases)
92
+ for entity in ordered:
93
+ other = {normalize(a) for a in items[entity]["aliases"]}
94
+ if entity in selected or aliases.intersection(other):
95
+ continue
96
+ selected.append(entity)
97
+ aliases.update(other)
98
+ if len(selected) == 4:
99
+ break
100
+ if len(selected) != 4:
101
+ raise ValueError("Need four distinct, unambiguous candidates")
102
+ # Correct position varies independently of model outputs.
103
+ return sorted(selected, key=lambda x: stable(f"position:{seed}:{fact['case_id']}:{x}"))
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_future.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exploratory kernel prediction and balanced multi-hop worlds, September 2026."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ ROOT = Path(__file__).resolve().parents[2]
12
+ CONFIG = ROOT / "configs/hebbian-future-v1.json"
13
+ ART = ROOT / "docs/development-artifacts/hebbian-future-v1"
14
+ DATA = ROOT / "data/hebbian-future-v1"
15
+ RESULTS = ROOT / "results/hebbian-future-v1"
16
+
17
+
18
+ def read(path):
19
+ return json.loads(Path(path).read_text())
20
+
21
+
22
+ def write(path, obj):
23
+ path = Path(path)
24
+ path.parent.mkdir(parents=True, exist_ok=True)
25
+ temporary = path.with_suffix(path.suffix + ".tmp")
26
+ temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
27
+ temporary.replace(path)
28
+
29
+
30
+ def digest(path):
31
+ h = hashlib.sha256()
32
+ with Path(path).open("rb") as handle:
33
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
34
+ h.update(block)
35
+ return h.hexdigest()
36
+
37
+
38
+ def unit(x):
39
+ x = np.asarray(x, dtype=np.float64)
40
+ return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12)
41
+
42
+
43
+ def chain_world(world, correlation, cfg):
44
+ """Match marginals, subjects, memberships and query exposure across correlations.
45
+
46
+ Eight people per organization: four combination-trained, four held out.
47
+ Within EACH split and organization exactly rho*4 have home==HQ. Other home
48
+ cities cycle identically across the balanced HQ city groups, keeping both
49
+ training/held-out home-city histograms uniform. ID permutations are shared.
50
+ """
51
+ n, groups, cities = (cfg[x] for x in ("people", "organizations", "cities"))
52
+ assert n == groups * 8 and groups % cities == 0
53
+ rng = np.random.default_rng(world + 918273)
54
+ people = rng.permutation(n).reshape(groups, 8)
55
+ headquarters = rng.permutation(np.arange(groups) % cities)
56
+ city_order = rng.permutation(cities)
57
+ membership = np.empty(n, dtype=int)
58
+ home = np.empty(n, dtype=int)
59
+ train = np.zeros(n, dtype=bool)
60
+ common_conflict = np.zeros(n, dtype=bool)
61
+ matches = int(correlation * 4)
62
+ for group, persons in enumerate(people):
63
+ membership[persons] = group
64
+ for split in range(2):
65
+ subset = persons[split * 4 : split * 4 + 4]
66
+ common_conflict[subset[-1]] = True
67
+ offsets = np.r_[np.zeros(matches, dtype=int), 1 + np.arange(4 - matches) % 3]
68
+ home[subset] = city_order[(headquarters[group] + offsets) % cities]
69
+ if split == 0:
70
+ train[subset] = True
71
+ headquarters = city_order[headquarters]
72
+ # Shared vocabulary and query positions; labels are next-token + EOS.
73
+ person_start, group_start, city_start = 10, 10 + n, 10 + n + groups
74
+ vocab = city_start + cities
75
+ member = np.stack(
76
+ [np.ones(n, int), person_start + np.arange(n), np.full(n, 3), np.full(n, 2)], axis=1
77
+ )
78
+ root = np.stack(
79
+ [
80
+ np.ones(groups, int),
81
+ group_start + np.arange(groups),
82
+ np.full(groups, 4),
83
+ np.full(groups, 2),
84
+ ],
85
+ axis=1,
86
+ )
87
+ resident = member.copy()
88
+ resident[:, 2] = 5
89
+ composite = member.copy()
90
+ composite[:, 2] = 6
91
+ return {
92
+ "world": world,
93
+ "correlation": correlation,
94
+ "vocab": vocab,
95
+ "membership": membership,
96
+ "home": home,
97
+ "headquarters": headquarters,
98
+ "train_people": train,
99
+ "common_conflict": common_conflict,
100
+ "member_x": member,
101
+ "root_x": root,
102
+ "home_x": resident,
103
+ "composite_x": composite,
104
+ "member_y": group_start + membership,
105
+ "root_y": city_start + headquarters,
106
+ "home_y": city_start + home,
107
+ "composite_y": city_start + headquarters[membership],
108
+ "group_start": group_start,
109
+ "city_start": city_start,
110
+ }
111
+
112
+
113
+ def training_arrays(world):
114
+ mask = world["train_people"]
115
+ x = np.concatenate(
116
+ [world[k + "_x"] for k in ("member", "root", "home")] + [world["composite_x"][mask]]
117
+ )
118
+ y = np.concatenate(
119
+ [world[k + "_y"] for k in ("member", "root", "home")] + [world["composite_y"][mask]]
120
+ )
121
+ return x, y
122
+
123
+
124
+ def ridge_predict(train_x, train_y, test_x, penalty=10.0):
125
+ """Fixed ridge linear probability model; statistics fitted on dev only."""
126
+ mean, scale = train_x.mean(0), np.maximum(train_x.std(0), 1e-8)
127
+ a = np.c_[np.ones(len(train_x)), (train_x - mean) / scale]
128
+ b = np.c_[np.ones(len(test_x)), (test_x - mean) / scale]
129
+ reg = np.eye(a.shape[1]) * penalty
130
+ reg[0, 0] = 0
131
+ beta = np.linalg.solve(a.T @ a + reg, a.T @ train_y)
132
+ return np.clip(b @ beta, 0, 1)
133
+
134
+
135
+ def auc(y, scores):
136
+ positive, negative = np.asarray(scores)[y == 1], np.asarray(scores)[y == 0]
137
+ if not len(positive) or not len(negative):
138
+ return None
139
+ return float(
140
+ (positive[:, None] > negative).mean() + 0.5 * (positive[:, None] == negative).mean()
141
+ )
142
+
143
+
144
+ def bootstrap_mean(values, seed, repeats=1000):
145
+ values = np.asarray(values)
146
+ rng = np.random.default_rng(seed)
147
+ means = values[rng.integers(len(values), size=(repeats, len(values)))].mean(1)
148
+ return [float(x) for x in np.quantile(means, [0.025, 0.975])]
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_interface.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired CE/MSE memory interfaces on the released synthetic recall task.
2
+
3
+ The official implementation supplies memory fitting, the reader, and batches.
4
+ This adapter fixes budgets and seeds, removes the future answer from inputs,
5
+ and records a complete crossing without selecting on the replacement mapping.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import importlib.metadata
12
+ import json
13
+ import platform
14
+ import sys
15
+ import time
16
+ from dataclasses import asdict
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+
23
+ ROOT = Path(__file__).resolve().parents[2]
24
+ DEFAULT_SPEC = {
25
+ "num_facts": 128,
26
+ "d_model": 64,
27
+ "hidden_dim": 256,
28
+ "junk_len": 9,
29
+ "junk_vocab_size": 9,
30
+ "batch_size": 256,
31
+ "mlp_epochs": 10000,
32
+ "mlp_lr": 0.001,
33
+ "mlp_min_lr": 1e-6,
34
+ "mlp_cutoff": -1.0,
35
+ "mlp_activation": "swish",
36
+ "mlp_bias": True,
37
+ "reader_steps": 4000,
38
+ "reader_lr": 2e-4,
39
+ "reader_weight_decay": 0.1,
40
+ "eval_every": 1000,
41
+ "eval_repeats": 8,
42
+ "cpu_threads": 1,
43
+ "source_path": "data/hebbian-interface-v1/source",
44
+ }
45
+
46
+
47
+ def _source(spec):
48
+ source = ROOT / spec["source_path"] / "src"
49
+ if str(source) not in sys.path:
50
+ sys.path.insert(0, str(source))
51
+
52
+
53
+ def tensor_hash(tensors):
54
+ """Hash names, shapes, dtypes and raw values, independently of serialization."""
55
+ digest = hashlib.sha256()
56
+ for name, value in sorted(tensors.items()):
57
+ tensor = value.detach().cpu().contiguous()
58
+ digest.update(f"{name}:{tuple(tensor.shape)}:{tensor.dtype}".encode())
59
+ digest.update(tensor.numpy().tobytes())
60
+ return digest.hexdigest()
61
+
62
+
63
+ def _state(model, *, non_mlp=False, frozen=False):
64
+ return {
65
+ name: value
66
+ for name, value in model.named_parameters()
67
+ if (not non_mlp or ".mlp." not in name) and (not frozen or not value.requires_grad)
68
+ }
69
+
70
+
71
+ def _memory_config(spec, loss, device):
72
+ from hebbian.mlp_core.mlp_gd import GDMLPConfig
73
+ from hebbian.mlp_core.task import SharedConstructionConfig
74
+
75
+ shared = SharedConstructionConfig(
76
+ build_dtype=torch.float32,
77
+ final_dtype=torch.float32,
78
+ device=str(device),
79
+ verbose=False,
80
+ )
81
+ shared.mlp_config.activation.activation = spec["mlp_activation"]
82
+ return GDMLPConfig(
83
+ shared=shared,
84
+ m=spec["hidden_dim"],
85
+ bias=spec["mlp_bias"],
86
+ num_epochs=spec["mlp_epochs"],
87
+ lr=spec["mlp_lr"],
88
+ min_lr=spec["mlp_min_lr"],
89
+ cutoff=spec["mlp_cutoff"],
90
+ loss_fn=loss,
91
+ batch_size=None,
92
+ eval_every=spec["eval_every"],
93
+ )
94
+
95
+
96
+ def _new_memory(spec, device):
97
+ from hebbian.mlp_core.mlp_gd import _create_gd_mlp
98
+
99
+ return _create_gd_mlp(spec["d_model"], spec["hidden_dim"], _memory_config(spec, "ce", device))
100
+
101
+
102
+ def make_config(spec, seed, device):
103
+ """The fixed SSFR architecture; memory and optimizer numbers come from spec."""
104
+ _source(spec)
105
+ from hebbian.transformer.config import AssociativeRecallConfig
106
+
107
+ config = AssociativeRecallConfig()
108
+ dc, tc = config.dataset_config, config.train_config
109
+ dc.num_facts = spec["num_facts"]
110
+ dc.junk_vocab_size = spec["junk_vocab_size"]
111
+ dc.min_seq_length = dc.max_seq_length = spec["junk_len"]
112
+ dc.custom_finalize()
113
+ tc.device, tc.dtype, tc.seed = str(device), torch.float32, seed
114
+ tc.embeddings_config.d_model = spec["d_model"]
115
+ tc.embeddings_config.tie_embeddings = True
116
+ tc.mlp_method, tc.mlp_hidden_dim = "gd", spec["hidden_dim"]
117
+ tc.batch_size, tc.steps_per_dataset = spec["batch_size"], spec["reader_steps"]
118
+ arch = tc.transformer_config
119
+ arch.n_layers = arch.n_head = 1
120
+ arch.use_identity_mlp = True
121
+ arch.mlp_residual = arch.attn_residual = False
122
+ arch.use_rope, arch.no_positional_encoding = False, True
123
+ arch.freeze_value_dense_identity = True
124
+ arch.mlp_norm_type = arch.lm_head_norm_type = "unit_rmsnorm"
125
+ arch.attn_norm_type, arch.bias = "rmsnorm", False
126
+ return config
127
+
128
+
129
+ def make_batches(spec, mapping, *, batch_size=None, num_batches=None):
130
+ """Author batches on CPU avoid a GPU synchronization per junk position."""
131
+ from hebbian.transformer.data import AssociativeRecallBatchGenerator
132
+
133
+ return AssociativeRecallBatchGenerator(
134
+ mapping,
135
+ spec["num_facts"],
136
+ spec["junk_vocab_size"],
137
+ spec["junk_len"],
138
+ spec["junk_len"],
139
+ batch_size or spec["batch_size"],
140
+ num_batches or spec["reader_steps"],
141
+ device=torch.device("cpu"),
142
+ )
143
+
144
+
145
+ def fixed_inputs(spec, mapping, seed):
146
+ """Balanced keys and independently seeded junk, with the answer removed."""
147
+ with torch.random.fork_rng(devices=[]):
148
+ torch.random.default_generator.manual_seed(seed)
149
+ keys = torch.arange(spec["num_facts"]).repeat_interleave(spec["eval_repeats"])
150
+ inputs, _ = next(iter(make_batches(spec, mapping, batch_size=len(keys), num_batches=1)))
151
+ inputs[:, spec["junk_len"]] = keys
152
+ return inputs[:, :-1].contiguous(), keys
153
+
154
+
155
+ def _errors(actual, expected):
156
+ relative = (actual - expected).norm(dim=-1) / expected.norm(dim=-1).clamp_min(1e-12)
157
+ cosine = F.cosine_similarity(actual, expected, dim=-1).clamp(-1, 1)
158
+ return relative, cosine.acos()
159
+
160
+
161
+ def _accuracy(scores, targets, changed):
162
+ correct = scores.argmax(-1).eq(targets)
163
+ return {
164
+ "accuracy_all": correct.float().mean().item(),
165
+ "accuracy_changed": correct[changed].float().mean().item() if changed.any() else None,
166
+ "n_all": targets.numel(),
167
+ "n_changed": int(changed.sum()),
168
+ }
169
+
170
+
171
+ def _save_arrays(path, **arrays):
172
+ np.savez_compressed(
173
+ path,
174
+ **{
175
+ name: value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else value
176
+ for name, value in arrays.items()
177
+ },
178
+ )
179
+
180
+
181
+ @torch.no_grad()
182
+ def standalone(memory, factset, embeddings, changed, path):
183
+ outputs = memory(factset.input_embeddings)
184
+ targets = torch.tensor(factset.mapping.outputs, device=outputs.device)
185
+ expected = factset.output_embeddings[targets]
186
+ relative, angle = _errors(outputs, expected)
187
+ normalized = F.normalize(outputs, dim=-1)
188
+ fact_scores = normalized @ factset.output_embeddings.T
189
+ full_scores = normalized @ embeddings.weight.T
190
+ norm_error = (outputs.norm(dim=-1) - expected.norm(dim=-1)).abs()
191
+ result = {
192
+ "fact_accuracy": fact_scores.argmax(-1).eq(targets).float().mean().item(),
193
+ "full_accuracy": full_scores.argmax(-1).eq(targets).float().mean().item(),
194
+ "relative_error_mean": relative.mean().item(),
195
+ "angle_radians_mean": angle.mean().item(),
196
+ "norm_error_mean": norm_error.mean().item(),
197
+ "output_norm_mean": outputs.norm(dim=-1).mean().item(),
198
+ "full_vocab": _accuracy(full_scores, targets, changed.to(outputs.device)),
199
+ "artifact": path.name,
200
+ }
201
+ _save_arrays(
202
+ path,
203
+ key=torch.arange(len(targets)),
204
+ target=targets,
205
+ changed_mapping=changed,
206
+ pred=full_scores.argmax(-1),
207
+ pred_fact=fact_scores.argmax(-1),
208
+ scores=full_scores,
209
+ scores_fact=fact_scores,
210
+ scores_fact_raw=outputs @ factset.output_embeddings.T,
211
+ relative_error=relative,
212
+ angle_radians=angle,
213
+ norm_error=norm_error,
214
+ output_norm=outputs.norm(dim=-1),
215
+ )
216
+ return result
217
+
218
+
219
+ @torch.no_grad()
220
+ def evaluate_reader(model, inputs, keys, targets, changed, embeddings, batch_size, path=None):
221
+ """Use actual query-position inputs to the MLP; never fit a predictor."""
222
+ device = next(model.parameters()).device
223
+ cuda_devices = [device.index or 0] if device.type == "cuda" else []
224
+ scores, queries = [], []
225
+ was_training = model.training
226
+ model.eval()
227
+ hook = model.transformer.h[0].mlp.register_forward_pre_hook(
228
+ lambda module, args: queries.append(args[0][:, -1].detach().cpu())
229
+ )
230
+ try:
231
+ with torch.random.fork_rng(devices=cuda_devices):
232
+ for batch in inputs.split(batch_size):
233
+ logits, _ = model(batch.to(device))
234
+ scores.append(logits[:, 0].cpu())
235
+ finally:
236
+ hook.remove()
237
+ model.train(was_training)
238
+ scores, queries = torch.cat(scores), torch.cat(queries)
239
+ relative, angle = _errors(queries, embeddings.weight.detach().cpu()[keys])
240
+ result = _accuracy(scores, targets, changed)
241
+ result.update(
242
+ {
243
+ "query_relative_error_mean": relative.mean().item(),
244
+ "query_angle_radians_mean": angle.mean().item(),
245
+ }
246
+ )
247
+ if path is not None:
248
+ _save_arrays(
249
+ path,
250
+ key=keys,
251
+ target=targets,
252
+ changed_mapping=changed,
253
+ pred=scores.argmax(-1),
254
+ scores=scores,
255
+ query_input=queries,
256
+ query_relative_error=relative,
257
+ query_angle_radians=angle,
258
+ )
259
+ result["artifact"] = path.name
260
+ return result
261
+
262
+
263
+ def load_checkpoint(path, device="cpu"):
264
+ """Load our tensor-only checkpoint; no refitting or custom-object unpickling."""
265
+ payload = torch.load(path, map_location="cpu", weights_only=True)
266
+ spec = payload["spec"]
267
+ _source(spec)
268
+ if payload["kind"] == "memory":
269
+ model = _new_memory(spec, device)
270
+ else:
271
+ from hebbian.transformer.model import GPT, GPTConfig
272
+
273
+ model = GPT(GPTConfig(**payload["gpt_config"])).to(device)
274
+ model.transformer.h[0].mlp = _new_memory(spec, device)
275
+ model.load_state_dict(payload["state_dict"], strict=True)
276
+ names = set(payload.get("trainable_names", []))
277
+ for name, parameter in model.named_parameters():
278
+ parameter.requires_grad_(name in names)
279
+ return model.eval(), payload
280
+
281
+
282
+ def run_world(spec, seed, output_dir, device):
283
+ """Fit four memories and two A-readers; evaluate all fixed final crossings."""
284
+ spec = {**DEFAULT_SPEC, **spec}
285
+ if (
286
+ min(
287
+ spec[k]
288
+ for k in (
289
+ "num_facts",
290
+ "d_model",
291
+ "hidden_dim",
292
+ "mlp_epochs",
293
+ "reader_steps",
294
+ "eval_every",
295
+ "eval_repeats",
296
+ )
297
+ )
298
+ <= 0
299
+ ):
300
+ raise ValueError("Dimensions and fixed training/evaluation budgets must be positive")
301
+ if spec["mlp_cutoff"] >= 0:
302
+ raise ValueError("This comparison requires the MLP loss cutoff to be disabled")
303
+ _source(spec)
304
+ from hebbian.transformer.fact_store import build_fact_mlp, build_factset, build_token_embeddings
305
+ from hebbian.transformer.model import GPT
306
+ from hebbian.transformer.train import _make_eval_factset
307
+ from hebbian.transformer.utils import (
308
+ copy_embeddings_to_gpt,
309
+ create_gpt_config,
310
+ insert_mlp_into_gpt,
311
+ )
312
+
313
+ output_dir = Path(output_dir)
314
+ output_dir.mkdir(parents=True, exist_ok=True)
315
+ device = torch.device(device)
316
+ torch.set_num_threads(spec["cpu_threads"])
317
+ torch.backends.cuda.matmul.allow_tf32 = False
318
+ torch.backends.cudnn.allow_tf32 = False
319
+ if device.type == "cuda":
320
+ torch.cuda.set_device(device)
321
+ torch.cuda.reset_peak_memory_stats(device)
322
+ started = time.perf_counter()
323
+ config = make_config(spec, seed, device)
324
+ factsets = {"A": build_factset(config, seed=seed)}
325
+ factsets["B"] = _make_eval_factset(factsets["A"], seed=seed + 7777)
326
+ embeddings = build_token_embeddings(
327
+ factsets["A"],
328
+ spec["junk_vocab_size"],
329
+ embedding_init="spherical",
330
+ dtype=torch.float32,
331
+ seed=seed,
332
+ ).to(device)
333
+ mappings = {name: torch.tensor(fs.mapping.outputs) for name, fs in factsets.items()}
334
+ changed = mappings["A"] != mappings["B"]
335
+ inputs, keys = fixed_inputs(spec, factsets["A"].mapping, seed + 20000)
336
+ _save_arrays(
337
+ output_dir / "world.npz",
338
+ inputs=inputs,
339
+ key=keys,
340
+ mapping_A=mappings["A"],
341
+ mapping_B=mappings["B"],
342
+ changed_mapping=changed,
343
+ embeddings=embeddings.weight,
344
+ )
345
+ summary = {
346
+ "seed": seed,
347
+ "spec": spec,
348
+ "state": "running",
349
+ "memories": {},
350
+ "readers": {},
351
+ "environment": {
352
+ "python": platform.python_version(),
353
+ "torch": torch.__version__,
354
+ "numpy": np.__version__,
355
+ "transformers": importlib.metadata.version("transformers"),
356
+ "cuda": torch.version.cuda,
357
+ "device": str(device),
358
+ "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
359
+ },
360
+ "world": {
361
+ "changed_facts": int(changed.sum()),
362
+ "facts": spec["num_facts"],
363
+ "test_inputs_hash": tensor_hash({"inputs": inputs}),
364
+ "mapping_A": mappings["A"].tolist(),
365
+ "mapping_B": mappings["B"].tolist(),
366
+ },
367
+ }
368
+
369
+ def persist():
370
+ temporary = output_dir / "summary.tmp"
371
+ temporary.write_text(json.dumps(summary, indent=2) + "\n")
372
+ temporary.replace(output_dir / "summary.json")
373
+
374
+ memories = {}
375
+ for loss in ("ce", "mse"):
376
+ memories[loss], summary["memories"][loss] = {}, {}
377
+ for name, factset in factsets.items():
378
+ stage = time.perf_counter()
379
+ torch.manual_seed(seed)
380
+ initial = _new_memory(spec, device)
381
+ initial_hash = tensor_hash(initial.state_dict())
382
+ del initial
383
+ memory, metrics = build_fact_mlp(
384
+ config, factset, method_config=_memory_config(spec, loss, device)
385
+ )
386
+ memory.eval().requires_grad_(False)
387
+ memories[loss][name] = memory
388
+ checkpoint = f"memory-{loss}-{name}.pt"
389
+ torch.save(
390
+ {
391
+ "kind": "memory",
392
+ "spec": spec,
393
+ "seed": seed,
394
+ "loss": loss,
395
+ "mapping": name,
396
+ "state_dict": {k: v.detach().cpu() for k, v in memory.state_dict().items()},
397
+ },
398
+ output_dir / checkpoint,
399
+ )
400
+ _save_arrays(
401
+ output_dir / f"memory-{loss}-{name}-curve.npz",
402
+ train_loss=np.asarray(metrics["train_losses"]),
403
+ )
404
+ assert len(metrics["train_losses"]) == spec["mlp_epochs"]
405
+ summary["memories"][loss][name] = {
406
+ "initial_hash": initial_hash,
407
+ "final_hash": tensor_hash(memory.state_dict()),
408
+ "seconds": time.perf_counter() - stage,
409
+ "checkpoint": checkpoint,
410
+ "training_final_loss": metrics["train_losses"][-1],
411
+ "training_final_fact_accuracy": metrics["final_accuracy"],
412
+ }
413
+ print(f"world {seed}: memory {loss}/{name} complete", flush=True)
414
+ persist()
415
+
416
+ models = {}
417
+ for loss in ("ce", "mse"):
418
+ stage = time.perf_counter()
419
+ torch.manual_seed(seed)
420
+ gpt_config = create_gpt_config(config.train_config, config.dataset_config)
421
+ model = GPT(gpt_config).to(device=device, dtype=torch.float32).eval()
422
+ copy_embeddings_to_gpt(model, embeddings)
423
+ insert_mlp_into_gpt(model, memories[loss]["A"], embeddings)
424
+ initial_hash = tensor_hash(_state(model, non_mlp=True))
425
+ frozen_before = tensor_hash(_state(model, frozen=True))
426
+ optimizer = model.configure_optimizers(
427
+ weight_decay=spec["reader_weight_decay"],
428
+ learning_rate=spec["reader_lr"],
429
+ betas=(0.9, 0.999),
430
+ device_type=device.type,
431
+ )
432
+ curve, stream_hash, train_loss_sum = [], hashlib.sha256(), 0.0
433
+ torch.manual_seed(seed + 10000)
434
+ for step, (batch, labels) in enumerate(make_batches(spec, factsets["A"].mapping), 1):
435
+ batch, labels = batch[:, :-1].contiguous(), labels[:, :-1].contiguous()
436
+ stream_hash.update(batch.numpy().tobytes())
437
+ stream_hash.update(labels[:, -1].numpy().tobytes())
438
+ model.train()
439
+ logits, _ = model(batch.to(device))
440
+ objective = F.cross_entropy(logits[:, 0], labels[:, -1].to(device))
441
+ optimizer.zero_grad(set_to_none=True)
442
+ objective.backward()
443
+ optimizer.step()
444
+ train_loss_sum += objective.item()
445
+ if step % spec["eval_every"] == 0 or step == spec["reader_steps"]:
446
+ evaluation = evaluate_reader(
447
+ model,
448
+ inputs,
449
+ keys,
450
+ mappings["A"][keys],
451
+ changed[keys],
452
+ embeddings,
453
+ spec["batch_size"],
454
+ )
455
+ curve.append(
456
+ {"step": step, "mean_training_loss": train_loss_sum / step, "A": evaluation}
457
+ )
458
+ print(
459
+ f"world {seed}: reader {loss} step {step}, A={evaluation['accuracy_all']:.4f}",
460
+ flush=True,
461
+ )
462
+ model.eval()
463
+ models[loss] = model
464
+ frozen_after = tensor_hash(_state(model, frozen=True))
465
+ assert frozen_after == frozen_before
466
+ checkpoint = f"reader-{loss}.pt"
467
+ torch.save(
468
+ {
469
+ "kind": "reader",
470
+ "spec": spec,
471
+ "seed": seed,
472
+ "loss": loss,
473
+ "gpt_config": asdict(gpt_config),
474
+ "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()},
475
+ "trainable_names": [k for k, v in model.named_parameters() if v.requires_grad],
476
+ },
477
+ output_dir / checkpoint,
478
+ )
479
+ summary["readers"][loss] = {
480
+ "initial_non_mlp_hash": initial_hash,
481
+ "final_non_mlp_hash": tensor_hash(_state(model, non_mlp=True)),
482
+ "frozen_hash_before": frozen_before,
483
+ "frozen_hash_after": frozen_after,
484
+ "training_stream_hash": stream_hash.hexdigest(),
485
+ "curve": curve,
486
+ "seconds": time.perf_counter() - stage,
487
+ "checkpoint": checkpoint,
488
+ "endpoints": {},
489
+ }
490
+ persist()
491
+
492
+ stage = time.perf_counter()
493
+ for loss, model in models.items():
494
+ for name in ("A", "B"):
495
+ summary["memories"][loss][name]["standalone"] = standalone(
496
+ memories[loss][name],
497
+ factsets[name],
498
+ embeddings,
499
+ changed,
500
+ output_dir / f"standalone-{loss}-{name}.npz",
501
+ )
502
+ conditions = {
503
+ "A": (memories[loss]["A"], "A"),
504
+ "wrong_A_on_B": (memories[loss]["A"], "B"),
505
+ "B_ce": (memories["ce"]["B"], "B"),
506
+ "B_mse": (memories["mse"]["B"], "B"),
507
+ }
508
+ for condition, (memory, target_map) in conditions.items():
509
+ insert_mlp_into_gpt(model.eval(), memory, embeddings)
510
+ result = evaluate_reader(
511
+ model,
512
+ inputs,
513
+ keys,
514
+ mappings[target_map][keys],
515
+ changed[keys],
516
+ embeddings,
517
+ spec["batch_size"],
518
+ output_dir / f"reader-{loss}-{condition}.npz",
519
+ )
520
+ summary["readers"][loss]["endpoints"][condition] = result
521
+ insert_mlp_into_gpt(model.eval(), memories[loss]["A"], embeddings)
522
+ assert (
523
+ tensor_hash(_state(model, non_mlp=True))
524
+ == summary["readers"][loss]["final_non_mlp_hash"]
525
+ )
526
+ initial_hashes = {
527
+ v["initial_hash"] for losses in summary["memories"].values() for v in losses.values()
528
+ }
529
+ summary["audits"] = {
530
+ "paired_memory_initializations": len(initial_hashes) == 1,
531
+ "paired_reader_initializations": len(
532
+ {r["initial_non_mlp_hash"] for r in summary["readers"].values()}
533
+ )
534
+ == 1,
535
+ "paired_training_streams": len(
536
+ {r["training_stream_hash"] for r in summary["readers"].values()}
537
+ )
538
+ == 1,
539
+ "frozen_parameters_unchanged": all(
540
+ r["frozen_hash_before"] == r["frozen_hash_after"] for r in summary["readers"].values()
541
+ ),
542
+ "future_answer_removed": inputs.shape[1] == 2 * spec["junk_len"] + 2,
543
+ "B_used_for_reader_optimization_or_selection": False,
544
+ }
545
+ assert all(
546
+ v
547
+ for k, v in summary["audits"].items()
548
+ if k != "B_used_for_reader_optimization_or_selection"
549
+ )
550
+ summary["cost"] = {
551
+ "memory_epochs_per_mapping_objective": spec["mlp_epochs"],
552
+ "memory_fact_exposures_per_mapping_objective": spec["mlp_epochs"] * spec["num_facts"],
553
+ "reader_steps_per_objective": spec["reader_steps"],
554
+ "reader_tokens_per_objective": spec["reader_steps"]
555
+ * spec["batch_size"]
556
+ * (2 * spec["junk_len"] + 2),
557
+ "reader_supervised_positions_per_objective": spec["reader_steps"] * spec["batch_size"],
558
+ "peak_gpu_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0,
559
+ }
560
+ summary["timing_seconds"] = {
561
+ "final_evaluation": time.perf_counter() - stage,
562
+ "whole_world": time.perf_counter() - started,
563
+ }
564
+ summary["state"] = "complete"
565
+ persist()
566
+ return summary
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_learning.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prospective Hebbian study: numerical calibration and auditable common primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.util
7
+ import json
8
+ import math
9
+ import os
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ ROOT = Path(__file__).resolve().parents[2]
16
+ DATA = ROOT / "data/hebbian-learning-v1"
17
+ RESULTS = ROOT / "results/hebbian-learning-v1"
18
+ ARTIFACTS = ROOT / "docs/development-artifacts/hebbian-learning-v1"
19
+ CONFIG_PATH = ROOT / "configs/hebbian-learning-v1.json"
20
+
21
+
22
+ def now():
23
+ return datetime.now(timezone.utc).isoformat()
24
+
25
+
26
+ def sha256(path):
27
+ h = hashlib.sha256()
28
+ with Path(path).open("rb") as f:
29
+ for block in iter(lambda: f.read(4 * 1024 * 1024), b""):
30
+ h.update(block)
31
+ return h.hexdigest()
32
+
33
+
34
+ def write_json(path, value):
35
+ path = Path(path)
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ tmp = path.with_name(path.name + f".{os.getpid()}.tmp")
38
+ tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
39
+ tmp.replace(path)
40
+
41
+
42
+ def read_json(path):
43
+ return json.loads(Path(path).read_text())
44
+
45
+
46
+ def config():
47
+ return read_json(CONFIG_PATH)
48
+
49
+
50
+ def first_crossing(values, threshold):
51
+ indices = np.flatnonzero(values <= threshold)
52
+ return int(indices[0]) if len(indices) else None
53
+
54
+
55
+ def mode_prediction(rho, lr, steps, initial):
56
+ factors = np.array([1 - lr * (1 + rho), 1 - lr * (1 - rho)])
57
+ if not np.all((factors > 0) & (factors < 1)):
58
+ raise ValueError("The declared monotone discrete regime is required")
59
+ return factors[None, :, None] ** np.arange(steps + 1)[:, None, None] * initial
60
+
61
+
62
+ def calibration_trajectory(phi, steps, lr, output_dim, checkpoint_nodes):
63
+ """Actual matrix SGD, compared against an independently computed recurrence."""
64
+ phi = np.asarray(phi, dtype=np.float64)
65
+ rho = float(phi[:, 0] @ phi[:, 1])
66
+ targets = np.eye(output_dim, 2, dtype=np.float64)
67
+ weight = np.zeros((output_dim, phi.shape[0]), dtype=np.float64)
68
+ modes = np.empty((steps + 1, 2, output_dim), dtype=np.float64)
69
+ checkpoints = {}
70
+ for step in range(steps + 1):
71
+ error = weight @ phi - targets
72
+ modes[step, 0] = (error[:, 0] + error[:, 1]) / math.sqrt(2)
73
+ modes[step, 1] = (error[:, 0] - error[:, 1]) / math.sqrt(2)
74
+ if step in checkpoint_nodes:
75
+ checkpoints[str(step)] = weight.copy()
76
+ if step < steps:
77
+ weight -= lr * (error @ phi.T)
78
+ predicted = mode_prediction(rho, lr, steps, modes[0])
79
+ norms = np.linalg.norm(modes, axis=2)
80
+ predicted_norms = np.linalg.norm(predicted, axis=2)
81
+ vector_errors = np.linalg.norm(modes - predicted, axis=2)
82
+ eligible = predicted_norms > norms[0] * 1e-6
83
+ max_relative = float(np.max(vector_errors[eligible] / predicted_norms[eligible]))
84
+ small_absolute = float(np.max(vector_errors[~eligible])) if (~eligible).any() else 0.0
85
+ crossings = []
86
+ for i, name in enumerate(["common", "difference"]):
87
+ for epsilon in [0.1, 0.01]:
88
+ factor = 1 - lr * (1 + rho if i == 0 else 1 - rho)
89
+ predicted_step = math.ceil(math.log(epsilon) / math.log(factor))
90
+ observed = first_crossing(norms[:, i], epsilon * norms[0, i])
91
+ crossings.append(
92
+ {
93
+ "mode": name,
94
+ "epsilon": epsilon,
95
+ "predicted_step": predicted_step,
96
+ "observed_step": observed,
97
+ "right_censored": observed is None,
98
+ "pass": (observed is None and predicted_step > steps)
99
+ or (observed is not None and abs(observed - predicted_step) <= 1),
100
+ }
101
+ )
102
+ summary = {
103
+ "rho": rho,
104
+ "max_relative_vector_error": max_relative,
105
+ "small_error_max_absolute": small_absolute,
106
+ "crossings": crossings,
107
+ "pass": max_relative <= 1e-7 and all(x["pass"] for x in crossings),
108
+ }
109
+ return summary, norms, predicted_norms, checkpoints
110
+
111
+
112
+ def calibrate():
113
+ import torch
114
+
115
+ cfg = config()["A"]
116
+ out = RESULTS / "A"
117
+ out.mkdir(parents=True, exist_ok=True)
118
+ source = DATA / "source/hebbian-mlps/src/hebbian/methods/hebbian/model.py"
119
+ spec = importlib.util.spec_from_file_location("locked_hebbian_model", source)
120
+ author = importlib.util.module_from_spec(spec)
121
+ spec.loader.exec_module(author)
122
+ summaries = []
123
+ for kind in ["exact", "bilinear"]:
124
+ for seed in cfg["seeds"]:
125
+ for rho in cfg["rho"]:
126
+ width = cfg["exact_width"] if kind == "exact" else cfg["input_dim"]
127
+ rng = np.random.default_rng(seed)
128
+ rotation = np.linalg.qr(rng.normal(size=(width, width)))[0]
129
+ inputs = rotation[:, :2] @ np.array([[1, rho], [0, np.sqrt(1 - rho**2)]])
130
+ if kind == "bilinear":
131
+ gen = torch.Generator().manual_seed(seed)
132
+ a0 = torch.randn(
133
+ cfg["bilinear_width"], width, generator=gen, dtype=torch.float64
134
+ )
135
+ a1 = torch.randn(
136
+ cfg["bilinear_width"], width, generator=gen, dtype=torch.float64
137
+ )
138
+ feature_map = author.BilinearFeatureMap(a0, a1, normalize=True)
139
+ raw_phi = feature_map(torch.from_numpy(inputs.T)).numpy().T
140
+ else:
141
+ raw_phi = inputs
142
+ phi = raw_phi / np.linalg.norm(raw_phi, axis=0)
143
+ summary, norms, prediction, weights = calibration_trajectory(
144
+ phi, cfg["steps"], cfg["lr"], cfg["output_dim"], cfg["checkpoints"]
145
+ )
146
+ run_id = f"{kind}-s{seed}-rho{rho}"
147
+ summary.update(
148
+ run_id=run_id,
149
+ kind=kind,
150
+ seed=seed,
151
+ input_rho=rho,
152
+ raw_gram=(raw_phi.T @ raw_phi).tolist(),
153
+ unit_gram=(phi.T @ phi).tolist(),
154
+ )
155
+ np.savez_compressed(
156
+ out / f"{run_id}.npz",
157
+ norms=norms,
158
+ prediction=prediction,
159
+ phi=phi,
160
+ **{f"weight_{k}": v for k, v in weights.items()},
161
+ )
162
+ summaries.append(summary)
163
+ print(run_id, summary["max_relative_vector_error"], summary["pass"], flush=True)
164
+ audit = {
165
+ "completed_at": now(),
166
+ "config_sha256": sha256(CONFIG_PATH),
167
+ "implementation_sha256": sha256(__file__),
168
+ "author_file_sha256": sha256(source),
169
+ "runs": summaries,
170
+ "pass": all(x["pass"] for x in summaries),
171
+ }
172
+ write_json(ARTIFACTS / "A/audit.json", audit)
173
+ if not audit["pass"]:
174
+ raise RuntimeError("Stage A failed numerical acceptance")
175
+ return audit
176
+
177
+
178
+ def q_auc(values, nodes):
179
+ values, nodes = np.asarray(values), np.asarray(nodes)
180
+ integrate = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
181
+ return integrate(values, nodes, axis=0) / nodes[-1]
182
+
183
+
184
+ def effective_rank(features):
185
+ z = features / np.maximum(np.linalg.norm(features, axis=1, keepdims=True), 1e-8)
186
+ gram = z @ z.T
187
+ return float(np.trace(gram) ** 2 / np.square(gram).sum())
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_model.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import hashlib
7
+ import os
8
+ import time
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
14
+
15
+ from .hebbian_data import TEMPLATE, score_answer
16
+ from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, write_json
17
+
18
+
19
+ def tensor_hash(tensor):
20
+ return hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
21
+
22
+
23
+ def state_hashes(model):
24
+ return {name: tensor_hash(p) for name, p in model.state_dict().items()}
25
+
26
+
27
+ def aggregate_hash(hashes):
28
+ return hashlib.sha256(
29
+ "\n".join(f"{k}:{v}" for k, v in sorted(hashes.items())).encode()
30
+ ).hexdigest()
31
+
32
+
33
+ def set_determinism(seed=0):
34
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
35
+ torch.set_num_threads(4)
36
+ torch.manual_seed(seed)
37
+ np.random.seed(seed)
38
+ torch.backends.cuda.matmul.allow_tf32 = False
39
+ torch.backends.cudnn.allow_tf32 = False
40
+ torch.backends.cudnn.benchmark = False
41
+ torch.use_deterministic_algorithms(True)
42
+
43
+
44
+ class QwenExperiment:
45
+ def __init__(self, device="cuda:3"):
46
+ set_determinism()
47
+ self.cfg = config()
48
+ self.device = torch.device(device)
49
+ source = DATA / "source/qwen3-0.6b-base"
50
+ self.tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True)
51
+ self.tokenizer.pad_token = self.tokenizer.eos_token
52
+ self.model = (
53
+ AutoModelForCausalLM.from_pretrained(
54
+ source,
55
+ local_files_only=True,
56
+ torch_dtype=torch.float32,
57
+ attn_implementation=self.cfg["model"]["attention"],
58
+ )
59
+ .to(self.device)
60
+ .eval()
61
+ )
62
+ self.model.requires_grad_(False)
63
+ self.layer = self.model.model.layers[self.cfg["model"]["layer"]]
64
+ self.mlp = self.layer.mlp
65
+ assert self.mlp.down_proj.weight.shape == (1024, 3072)
66
+ assert self.mlp.up_proj.weight.numel() + self.mlp.gate_proj.weight.numel() == 6291456
67
+ self.base_local = {n: p.detach().clone() for n, p in self.mlp.named_parameters()}
68
+ self.reference = None
69
+
70
+ def restore_base(self):
71
+ with torch.no_grad():
72
+ for n, p in self.mlp.named_parameters():
73
+ p.copy_(self.base_local[n])
74
+
75
+ def configure_trainable(self, phase):
76
+ self.model.requires_grad_(False)
77
+ names = ["down_proj.weight"] if phase == "adapt" else ["up_proj.weight", "gate_proj.weight"]
78
+ for name, p in self.mlp.named_parameters():
79
+ p.requires_grad_(name in names)
80
+ return [p for p in self.model.parameters() if p.requires_grad]
81
+
82
+ def make_reference(self):
83
+ self.reference = copy.deepcopy(self.model).eval().requires_grad_(False)
84
+
85
+ def rows(self, records, views=(0,)):
86
+ return [(r, v, r["encoded"][v]) for r in records for v in views]
87
+
88
+ def batch(self, encoded, prompt_only=False):
89
+ sequences = [
90
+ x["input_ids"][: x["answer_start"]] if prompt_only else x["input_ids"] for x in encoded
91
+ ]
92
+ width = max(map(len, sequences))
93
+ ids = torch.full(
94
+ (len(sequences), width),
95
+ self.tokenizer.pad_token_id,
96
+ dtype=torch.long,
97
+ device=self.device,
98
+ )
99
+ attention = torch.zeros_like(ids)
100
+ answer = torch.zeros_like(ids, dtype=torch.bool)
101
+ for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)):
102
+ ids[i, : len(seq)] = torch.tensor(seq, device=self.device)
103
+ attention[i, : len(seq)] = 1
104
+ if not prompt_only:
105
+ answer[i, : len(seq)] = torch.tensor(enc["loss_mask"], device=self.device).bool()
106
+ return ids, attention, answer
107
+
108
+ def hidden(self, ids, attention, model=None):
109
+ return (
110
+ (model or self.model)
111
+ .model(input_ids=ids, attention_mask=attention, use_cache=False)
112
+ .last_hidden_state
113
+ )
114
+
115
+ def ce(self, encoded, model=None):
116
+ ids, attention, mask = self.batch(encoded)
117
+ hidden = self.hidden(ids, attention, model)
118
+ b, t = torch.where(mask[:, 1:])
119
+ logits = (model or self.model).lm_head(hidden[b, t])
120
+ losses = F.cross_entropy(logits, ids[b, t + 1], reduction="none")
121
+ sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses)
122
+ counts = torch.bincount(b, minlength=len(encoded))
123
+ return sums / counts
124
+
125
+ def kl(self, encoded):
126
+ if self.reference is None:
127
+ raise RuntimeError("An episode-specific parent reference is required")
128
+ ids, attention, mask = self.batch(encoded)
129
+ b, t = torch.where(mask[:, 1:])
130
+ with torch.no_grad():
131
+ ref_hidden = self.hidden(ids, attention, self.reference)
132
+ ref_log = F.log_softmax(self.reference.lm_head(ref_hidden[b, t]), dim=-1)
133
+ logits = self.model.lm_head(self.hidden(ids, attention)[b, t])
134
+ losses = F.kl_div(
135
+ F.log_softmax(logits, dim=-1), ref_log, reduction="none", log_target=True
136
+ ).sum(-1)
137
+ sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses)
138
+ return sums / torch.bincount(b, minlength=len(encoded))
139
+
140
+ def features(self, encoded, detach=True):
141
+ captured = {}
142
+
143
+ def capture(module, args):
144
+ captured["phi"] = args[0]
145
+
146
+ def capture_input(module, args):
147
+ captured["x"] = args[0]
148
+
149
+ handle = self.mlp.down_proj.register_forward_pre_hook(capture)
150
+ input_handle = self.mlp.register_forward_pre_hook(capture_input)
151
+ try:
152
+ ids, attention, _ = self.batch(encoded, prompt_only=True)
153
+ if detach:
154
+ with torch.no_grad():
155
+ hidden = self.hidden(ids, attention)
156
+ positions = attention.sum(1) - 1
157
+ self.last_prompt_logits = self.model.lm_head(
158
+ hidden[torch.arange(len(encoded), device=self.device), positions]
159
+ ).detach()
160
+ x = captured["x"][torch.arange(len(encoded), device=self.device), positions]
161
+ self.last_layer_inputs = x.detach()
162
+ self.original_features = (
163
+ F.linear(x, self.base_local["up_proj.weight"])
164
+ * F.silu(F.linear(x, self.base_local["gate_proj.weight"]))
165
+ ).detach()
166
+ else:
167
+ self.hidden(ids, attention)
168
+ phi = captured["phi"][
169
+ torch.arange(len(encoded), device=self.device), attention.sum(1) - 1
170
+ ]
171
+ return phi.detach() if detach else phi
172
+ finally:
173
+ handle.remove()
174
+ input_handle.remove()
175
+
176
+ @torch.no_grad()
177
+ def generate(self, prompts, max_new_tokens=24):
178
+ # Left-padding generation; positions are computed from the attention mask.
179
+ self.tokenizer.padding_side = "left"
180
+ inputs = self.tokenizer(
181
+ prompts, padding=True, return_tensors="pt", add_special_tokens=False
182
+ ).to(self.device)
183
+ prompt_width = inputs.input_ids.shape[1]
184
+ tokenizer = self.tokenizer
185
+
186
+ class StopAtNewline(StoppingCriteria):
187
+ def __call__(self, input_ids, scores, **kwargs):
188
+ texts = tokenizer.batch_decode(
189
+ input_ids[:, prompt_width:], skip_special_tokens=True
190
+ )
191
+ return torch.tensor(["\n" in text for text in texts], device=input_ids.device)
192
+
193
+ output = self.model.generate(
194
+ **inputs,
195
+ do_sample=False,
196
+ max_new_tokens=max_new_tokens,
197
+ pad_token_id=self.tokenizer.pad_token_id,
198
+ eos_token_id=self.tokenizer.eos_token_id,
199
+ use_cache=True,
200
+ logits_to_keep=1,
201
+ stopping_criteria=StoppingCriteriaList([StopAtNewline()]),
202
+ )
203
+ tail = output[:, inputs.input_ids.shape[1] :]
204
+ predictions = self.tokenizer.batch_decode(tail, skip_special_tokens=True)
205
+ # Padding after a newline stop is not evidence of the model emitting EOS.
206
+ eos_emitted = []
207
+ for row in tail:
208
+ emitted = False
209
+ for length, token in enumerate(row, 1):
210
+ if int(token) == self.tokenizer.eos_token_id:
211
+ emitted = True
212
+ break
213
+ if "\n" in self.tokenizer.decode(row[:length], skip_special_tokens=True):
214
+ break
215
+ eos_emitted.append(emitted)
216
+ return predictions, eos_emitted
217
+
218
+ @torch.no_grad()
219
+ def evaluate(self, records, views=(0, 1, 2), batch_size=24):
220
+ rows = self.rows(records, views)
221
+ result = []
222
+ for start in range(0, len(rows), batch_size):
223
+ chunk = rows[start : start + batch_size]
224
+ encoded = [x[2] for x in chunk]
225
+ losses = self.ce(encoded).tolist()
226
+ predictions, eos = self.generate([TEMPLATE.format(r["views"][v]) for r, v, _ in chunk])
227
+ phi = self.features(encoded)
228
+ for i, (r, v, enc) in enumerate(chunk):
229
+ prediction = predictions[i]
230
+ first_token = enc["input_ids"][enc["answer_start"]]
231
+ logits = self.last_prompt_logits[i]
232
+ competitor_logits = logits.clone()
233
+ competitor_logits[first_token] = -torch.inf
234
+ competitor = int(competitor_logits.argmax())
235
+ result.append(
236
+ {
237
+ "case_id": r["case_id"],
238
+ "relation_id": r["relation_id"],
239
+ "subject_group": r["subject_group"],
240
+ "view_id": v,
241
+ "answer_nll": losses[i],
242
+ "prediction": prediction,
243
+ "answer_em": score_answer(prediction, r.get("aliases", [r["answer"]])),
244
+ "eos_emitted": eos[i],
245
+ "feature_norm": float(phi[i].norm()),
246
+ "first_answer_nll": float(-logits.log_softmax(-1)[first_token]),
247
+ "first_answer_margin": float(logits[first_token] - logits[competitor]),
248
+ "current_competitor_token": competitor,
249
+ "answer_tokens": enc["answer_tokens"],
250
+ "prompt_tokens": enc["prompt_tokens"],
251
+ }
252
+ )
253
+ return result
254
+
255
+ def gradient(self, encoded):
256
+ loss = self.ce([encoded]).mean()
257
+ grad = torch.autograd.grad(loss, self.mlp.down_proj.weight)[0]
258
+ return grad.detach(), float(loss.detach())
259
+
260
+ def verify_hooks_and_gradients(self, encoded):
261
+ self.configure_trainable("adapt")
262
+ captured = {}
263
+
264
+ def capture_input(module, args):
265
+ captured["x"] = args[0].detach()
266
+
267
+ def capture_down(module, args, output):
268
+ captured["phi"] = args[0].detach()
269
+ output.retain_grad()
270
+ captured["output"] = output
271
+
272
+ handles = [
273
+ self.mlp.register_forward_pre_hook(capture_input),
274
+ self.mlp.down_proj.register_forward_hook(capture_down),
275
+ ]
276
+ try:
277
+ self.model.zero_grad(set_to_none=True)
278
+ self.ce([encoded]).mean().backward()
279
+ with torch.no_grad():
280
+ expected_phi = self.mlp.up_proj(captured["x"]) * F.silu(
281
+ self.mlp.gate_proj(captured["x"])
282
+ )
283
+ phi_error = float((expected_phi - captured["phi"]).abs().max())
284
+ delta = captured["output"].grad.double().flatten(0, 1)
285
+ phi = captured["phi"].double().flatten(0, 1)
286
+ reconstructed = delta.T @ phi
287
+ actual = self.mlp.down_proj.weight.grad.double()
288
+ grad_error = float((reconstructed - actual).norm() / actual.norm())
289
+ nonanswer_positions = encoded["answer_start"] - 1
290
+ prompt_grad_norm = float(delta[:nonanswer_positions].norm())
291
+ assert phi_error == 0.0
292
+ assert grad_error < 1e-5
293
+ return {
294
+ "phi_max_absolute_error": phi_error,
295
+ "gradient_relative_error": grad_error,
296
+ "earlier_prompt_delta_norm": prompt_grad_norm,
297
+ "all_positions_used": True,
298
+ "trainable_parameters": sum(
299
+ p.numel() for p in self.model.parameters() if p.requires_grad
300
+ ),
301
+ "pass": True,
302
+ }
303
+ finally:
304
+ for handle in handles:
305
+ handle.remove()
306
+ self.model.zero_grad(set_to_none=True)
307
+
308
+
309
+ def run_baseline(device, shard=0, shards=1):
310
+ engine = QwenExperiment(device)
311
+ candidates = read_json(DATA / "candidates.json")[shard::shards]
312
+ out = DATA / f"baseline-shard-{shard}.jsonl"
313
+ finished = {}
314
+ if out.exists():
315
+ for line in out.read_text().splitlines():
316
+ row = __import__("json").loads(line)
317
+ finished[row["case_id"]] = row
318
+ candidates = [r for r in candidates if r["case_id"] not in finished]
319
+ start_time = time.monotonic()
320
+ for start in range(0, len(candidates), 8):
321
+ chunk = candidates[start : start + 8]
322
+ rows = engine.evaluate(chunk)
323
+ with out.open("a") as f:
324
+ for record in chunk:
325
+ item = {
326
+ "case_id": record["case_id"],
327
+ "views": [r for r in rows if r["case_id"] == record["case_id"]],
328
+ }
329
+ f.write(__import__("json").dumps(item, ensure_ascii=False) + "\n")
330
+ if start % 80 == 0:
331
+ print(
332
+ f"baseline shard={shard} {start + len(chunk)}/{len(candidates)} "
333
+ f"elapsed={time.monotonic() - start_time:.1f}s",
334
+ flush=True,
335
+ )
336
+ write_json(
337
+ ARTIFACTS / f"baseline-shard-{shard}-complete.json",
338
+ {"time": now(), "rows": len(candidates) + len(finished), "shards": shards},
339
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_statistics.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Development-only predictor fitting and episode-cluster paired inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+
7
+ import numpy as np
8
+
9
+ from .hebbian_learning import (
10
+ ARTIFACTS,
11
+ DATA,
12
+ RESULTS,
13
+ config,
14
+ now,
15
+ q_auc,
16
+ read_json,
17
+ sha256,
18
+ write_json,
19
+ )
20
+
21
+
22
+ def fit_ridge(x, y, alpha):
23
+ mean, scale = x.mean(0), x.std(0)
24
+ scale = np.where(scale > 1e-12, scale, 1)
25
+ z = (x - mean) / scale
26
+ intercept = float(y.mean())
27
+ coef = np.linalg.solve(z.T @ z + alpha * np.eye(z.shape[1]), z.T @ (y - intercept))
28
+ return {
29
+ "mean": mean.tolist(),
30
+ "scale": scale.tolist(),
31
+ "coefficients": coef.tolist(),
32
+ "intercept": intercept,
33
+ "alpha": alpha,
34
+ "n_features": x.shape[1],
35
+ }
36
+
37
+
38
+ def predict(model, x):
39
+ x = x[:, : model["n_features"]]
40
+ return ((x - model["mean"]) / model["scale"]) @ np.array(model["coefficients"]) + model[
41
+ "intercept"
42
+ ]
43
+
44
+
45
+ def fact_trajectories(path):
46
+ evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))]
47
+ nodes = [e["rows"][0]["step"] for e in evaluations]
48
+ by_node = [{(r["case_id"], r["view_id"]): r for r in e["rows"]} for e in evaluations]
49
+ cases = sorted({r["case_id"] for r in evaluations[0]["rows"]})
50
+ result = []
51
+ for case in cases:
52
+ rewrite = [np.mean([rows[case, v]["answer_em"] for v in [1, 2]]) for rows in by_node]
53
+ standard = [rows[case, 0]["answer_em"] for rows in by_node]
54
+ all_correct = [all(rows[case, v]["answer_em"] for v in range(3)) for rows in by_node]
55
+ sustained = next(
56
+ (i for i in range(len(nodes) - 1) if all_correct[i] and all_correct[i + 1]), None
57
+ )
58
+ first = by_node[0][case, 0]
59
+ result.append(
60
+ {
61
+ "case_id": case,
62
+ "q_auc": float(q_auc(rewrite, nodes)),
63
+ "q_gain_auc": float(q_auc(np.array(rewrite) - rewrite[0], nodes)),
64
+ "standard_auc": float(q_auc(standard, nodes)),
65
+ "nodes": nodes,
66
+ "rewrite_accuracy": rewrite,
67
+ "standard_accuracy": standard,
68
+ "sustained_step": nodes[sustained] if sustained is not None else None,
69
+ "sustained_exposures": by_node[sustained][case, 0]["exposures"]
70
+ if sustained is not None
71
+ else None,
72
+ "endpoint_first_success": sustained is None and all_correct[-1],
73
+ "right_censored": sustained is None,
74
+ "relation_id": first["relation_id"],
75
+ }
76
+ )
77
+ return result
78
+
79
+
80
+ def freeze_b():
81
+ from .hebbian_train import frozen_training_sources, run_summary, select_config
82
+
83
+ episodes = read_json(DATA / "episodes.json")["B_dev"]
84
+ candidates = []
85
+ for lr in config()["adapt"]["learning_rates"]:
86
+ summaries = [run_summary(RESULTS / f"B/dev-lr{lr:g}-e{i}") for i in range(len(episodes))]
87
+ candidates.append(
88
+ {
89
+ "learning_rate": lr,
90
+ "q_auc": float(np.mean([s["q_auc"] for s in summaries])),
91
+ "keep_damage": float(np.mean([s["keep_damage"] for s in summaries])),
92
+ "episodes": summaries,
93
+ }
94
+ )
95
+ chosen = select_config(candidates, "q_auc", True)
96
+ lr = chosen["learning_rate"]
97
+ x, y, groups = [], [], []
98
+ for episode in range(len(episodes)):
99
+ path = RESULTS / f"B/dev-lr{lr:g}-e{episode}"
100
+ if not (path / "complete.json").exists():
101
+ raise RuntimeError("All B_dev runs must have completion receipts")
102
+ outcomes = {r["case_id"]: r["q_auc"] for r in fact_trajectories(path)}
103
+ for row in read_json(path / "prospective-features.json")["rows"]:
104
+ x.append(row["features"])
105
+ y.append(outcomes[row["case_id"]])
106
+ groups.append(episode)
107
+ x, y, groups = np.array(x), np.array(y), np.array(groups)
108
+ predictors = {}
109
+ for name, width in [("P0", 4), ("P1", 8), ("P2", 10)]:
110
+ scores = {}
111
+ for alpha in config()["statistics"]["ridge_grid"]:
112
+ errors = []
113
+ for group in np.unique(groups):
114
+ train = groups != group
115
+ model = fit_ridge(x[train, :width], y[train], alpha)
116
+ errors.append(np.mean(np.abs(predict(model, x[~train]) - y[~train])))
117
+ scores[alpha] = float(np.mean(errors))
118
+ best_alpha = min(scores, key=scores.get)
119
+ predictors[name] = {**fit_ridge(x[:, :width], y, best_alpha), "cv_mae": scores}
120
+ write_json(
121
+ ARTIFACTS / "B-lock.json",
122
+ {
123
+ "time": now(),
124
+ "status": "locked",
125
+ "learning_rate": lr,
126
+ "lr_candidates": candidates,
127
+ "predictors": predictors,
128
+ "source_hashes": frozen_training_sources(),
129
+ "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
130
+ "fitting_scope": "B_dev only; fold-specific training standardization in episode CV",
131
+ },
132
+ )
133
+
134
+
135
+ def paired_inference(differences):
136
+ differences = np.asarray(differences, dtype=np.float64)
137
+ rng = np.random.default_rng(config()["statistics"]["seed"])
138
+ n = len(differences)
139
+ samples = differences[rng.integers(0, n, (10000, n))].mean(1)
140
+ observed = float(differences.mean())
141
+ signs = np.array(list(itertools.product([-1, 1], repeat=n)))
142
+ p = float(np.mean(np.abs((signs * differences).mean(1)) >= abs(observed) - 1e-14))
143
+ return {
144
+ "mean": observed,
145
+ "ci95": np.quantile(samples, [0.025, 0.975]).tolist(),
146
+ "exact_two_sided_sign_p": p,
147
+ "episode_differences": differences.tolist(),
148
+ "n_episodes": n,
149
+ }
150
+
151
+
152
+ def rankdata(values):
153
+ values = np.asarray(values)
154
+ order = np.argsort(values, kind="stable")
155
+ ranked = np.empty(len(values), dtype=float)
156
+ i = 0
157
+ while i < len(values):
158
+ j = i + 1
159
+ while j < len(values) and values[order[j]] == values[order[i]]:
160
+ j += 1
161
+ ranked[order[i:j]] = (i + j - 1) / 2
162
+ i = j
163
+ return ranked
164
+
165
+
166
+ def spearman(x, y):
167
+ a, b = rankdata(x), rankdata(y)
168
+ return float(np.corrcoef(a, b)[0, 1]) if a.std() and b.std() else None
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_train.py ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired formation/adaptation, prospective diagnostics and exact state resumption."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ import random
8
+ import time
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+
14
+ from .hebbian_learning import (
15
+ ARTIFACTS,
16
+ CONFIG_PATH,
17
+ DATA,
18
+ RESULTS,
19
+ ROOT,
20
+ config,
21
+ effective_rank,
22
+ now,
23
+ q_auc,
24
+ read_json,
25
+ sha256,
26
+ write_json,
27
+ )
28
+ from .hebbian_model import (
29
+ QwenExperiment,
30
+ aggregate_hash,
31
+ set_determinism,
32
+ state_hashes,
33
+ )
34
+
35
+
36
+ def grouping(records, seed):
37
+ """Exact minimum-cost derangements; random seeded ties, real CE labels unchanged."""
38
+ n = len(records)
39
+ rng = np.random.default_rng(seed)
40
+ permutations = [
41
+ p for p in itertools.permutations(range(n)) if all(i != j for i, j in enumerate(p))
42
+ ]
43
+
44
+ def cost(p):
45
+ return sum(
46
+ 10 * (records[i]["target_id"] == records[j]["target_id"])
47
+ + (records[i]["relation_id"] != records[j]["relation_id"])
48
+ for i, j in enumerate(p)
49
+ )
50
+
51
+ costs = np.array([cost(p) for p in permutations])
52
+ best = np.flatnonzero(costs == costs.min())
53
+ p1, p2 = [permutations[int(rng.choice(best))] for _ in range(2)]
54
+ groups = [(3 * i, 3 * p1[i] + 1, 3 * p2[i] + 2) for i in range(n)]
55
+ return groups
56
+
57
+
58
+ def contrastive_loss(features, target_ids, groups, tau=0.1):
59
+ z = F.normalize(features, dim=-1, eps=1e-8)
60
+ similarities = z @ z.T / tau
61
+ positive = torch.zeros_like(similarities, dtype=torch.bool)
62
+ for group in groups:
63
+ for i in group:
64
+ for j in group:
65
+ if i != j:
66
+ positive[i, j] = True
67
+ negative = torch.tensor([[a != b for b in target_ids] for a in target_ids], device=z.device)
68
+ negative &= ~positive
69
+ negative.fill_diagonal_(False)
70
+ assert torch.all(positive.sum(1) == 2)
71
+ assert torch.all(negative.sum(1) >= 1)
72
+ allowed = positive | negative
73
+ log_denominator = similarities.masked_fill(~allowed, -torch.inf).logsumexp(1)
74
+ loss = (log_denominator - (similarities * positive).sum(1) / positive.sum(1)).mean()
75
+ return loss, {"positive_pairs": int(positive.sum()), "negative_pairs": int(negative.sum())}
76
+
77
+
78
+ def optimizer(parameters, lr):
79
+ cfg = config()["optimizer"]
80
+ return torch.optim.AdamW(
81
+ parameters,
82
+ lr=lr,
83
+ betas=tuple(cfg["betas"]),
84
+ eps=cfg["eps"],
85
+ weight_decay=cfg["weight_decay"],
86
+ )
87
+
88
+
89
+ def replay_batch(pools, texts, step):
90
+ facts = pools["R_keep"]
91
+ return [facts[(step * 6 + i) % len(facts)]["encoded"][0] for i in range(6)] + [
92
+ texts["train"][(step * 2 + i) % len(texts["train"])] for i in range(2)
93
+ ]
94
+
95
+
96
+ def frozen_training_sources():
97
+ paths = [CONFIG_PATH] + sorted((ROOT / "src/llm_memory_editability").glob("hebbian*.py"))
98
+ paths += [ROOT / "scripts/run_hebbian_learning.py"]
99
+ return {str(p.relative_to(ROOT)): sha256(p) for p in paths}
100
+
101
+
102
+ def save_checkpoint(path, engine, opt, step, meta, ledger):
103
+ state = {
104
+ "parameters": {n: p.detach().cpu().clone() for n, p in engine.mlp.named_parameters()},
105
+ "optimizer": opt.state_dict(),
106
+ "step": step,
107
+ "data_cursor": step,
108
+ "torch_rng": torch.get_rng_state(),
109
+ "cuda_rng": torch.cuda.get_rng_state(engine.device)
110
+ if engine.device.type == "cuda"
111
+ else None,
112
+ "numpy_rng": np.random.get_state(),
113
+ "python_rng": random.getstate(),
114
+ "meta": meta,
115
+ "ledger": ledger,
116
+ }
117
+ tmp = path.with_name(path.name + ".tmp")
118
+ torch.save(state, tmp)
119
+ tmp.replace(path)
120
+
121
+
122
+ def restore_checkpoint(path, engine, opt, meta):
123
+ state = torch.load(path, map_location="cpu", weights_only=False)
124
+ if state["meta"] != meta:
125
+ raise RuntimeError(f"Checkpoint contract differs: {path}")
126
+ with torch.no_grad():
127
+ for n, p in engine.mlp.named_parameters():
128
+ p.copy_(state["parameters"][n])
129
+ opt.load_state_dict(state["optimizer"])
130
+ torch.set_rng_state(state["torch_rng"])
131
+ if state["cuda_rng"] is not None:
132
+ torch.cuda.set_rng_state(state["cuda_rng"], engine.device)
133
+ np.random.set_state(state["numpy_rng"])
134
+ random.setstate(state["python_rng"])
135
+ return state["step"], state["ledger"]
136
+
137
+
138
+ def load_parent(engine, parent_path=None):
139
+ engine.restore_base()
140
+ if parent_path is not None:
141
+ state = torch.load(parent_path, map_location="cpu", weights_only=False)
142
+ with torch.no_grad():
143
+ for n, p in engine.mlp.named_parameters():
144
+ p.copy_(state["parameters"][n])
145
+
146
+
147
+ def gradient_cos(a, b):
148
+ a, b = a.double(), b.double()
149
+ return float((a * b).sum() / (a.norm() * b.norm()).clamp_min(1e-30))
150
+
151
+
152
+ def diagnose_episode(engine, records, replay, lr, out):
153
+ """Saved before the learning trajectory; Adam candidate uses training data only."""
154
+ engine.configure_trainable("adapt")
155
+ p = engine.mlp.down_proj.weight
156
+ original = p.detach().clone()
157
+ encoded = [r["encoded"][v] for r in records for v in range(3)]
158
+ features = engine.features(encoded).double().cpu().numpy().reshape(len(records), 3, -1)
159
+ unit = features / np.maximum(np.linalg.norm(features, axis=-1, keepdims=True), 1e-8)
160
+ p0_gram = unit[:, 0] @ unit[:, 0].T
161
+ rank = effective_rank(features[:, 0])
162
+ opt = optimizer([p], lr)
163
+ opt.zero_grad(set_to_none=True)
164
+ (engine.ce([r["encoded"][0] for r in records[:8]]).mean() + engine.kl(replay).mean()).backward()
165
+ torch.nn.utils.clip_grad_norm_([p], 1.0)
166
+ opt.step()
167
+ delta = (p.detach() - original).clone()
168
+ with torch.no_grad():
169
+ p.copy_(original)
170
+ torch.save(
171
+ {"delta_B": delta.cpu(), "phi": torch.from_numpy(features)}, out / "initial-diagnostics.pt"
172
+ )
173
+ diagnostic = []
174
+ for i, record in enumerate(records):
175
+ grads, losses = zip(*(engine.gradient(enc) for enc in record["encoded"]), strict=True)
176
+ other = [
177
+ p0_gram[i, j] for j, r in enumerate(records) if r["target_id"] != record["target_id"]
178
+ ]
179
+ if not other:
180
+ raise ValueError("Each episode needs different-answer facts")
181
+ norms = np.linalg.norm(features[i], axis=1)
182
+ feature_values = [
183
+ losses[0],
184
+ record["encoded"][0]["answer_tokens"],
185
+ record["encoded"][0]["prompt_tokens"],
186
+ float(grads[0].double().norm()),
187
+ float(np.mean(unit[i, 1:] @ unit[i, 0])),
188
+ float(max(other)),
189
+ float(norms[1:].mean() / norms[0]),
190
+ rank,
191
+ float(np.mean([gradient_cos(grads[0], g) for g in grads[1:]])),
192
+ float(np.mean([float((g.double() * delta.double()).sum()) for g in grads[1:]])),
193
+ ]
194
+ diagnostic.append(
195
+ {
196
+ "case_id": record["case_id"],
197
+ "features": feature_values,
198
+ "p0_p1_cos": float(unit[i, 0] @ unit[i, 1]),
199
+ "p0_p2_cos": float(unit[i, 0] @ unit[i, 2]),
200
+ "feature_norms": norms.tolist(),
201
+ "initial_nll": list(losses),
202
+ }
203
+ )
204
+ engine.model.zero_grad(set_to_none=True)
205
+ assert torch.equal(p, original)
206
+ write_json(
207
+ out / "prospective-features.json",
208
+ {
209
+ "saved_at": now(),
210
+ "rows": diagnostic,
211
+ "information": {
212
+ "P0": "initial answer NLL, lengths, labeled training gradient norm",
213
+ "P1": "P0 plus prompt-only phi geometry",
214
+ "P2": "P1 plus labeled evaluation gradients and training-only Adam candidate",
215
+ },
216
+ },
217
+ )
218
+ return diagnostic
219
+
220
+
221
+ def first_order_calibration(engine, record, out):
222
+ parameter = engine.mlp.down_proj.weight
223
+ initial = parameter.detach().clone()
224
+ source_grad, _ = engine.gradient(record["encoded"][0])
225
+ rows = []
226
+ for view in [1, 2]:
227
+ encoded = record["encoded"][view]
228
+ grad, nll0 = engine.gradient(encoded)
229
+ ids, attention, _ = engine.batch([encoded], prompt_only=True)
230
+ answer_token = encoded["input_ids"][encoded["answer_start"]]
231
+ logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1])
232
+ competitor_logits = logits.detach().clone()
233
+ competitor_logits[answer_token] = -torch.inf
234
+ competitor = int(competitor_logits.argmax())
235
+ margin = logits[answer_token] - logits[competitor]
236
+ margin_grad = torch.autograd.grad(margin, parameter)[0].detach()
237
+ margin0 = float(margin.detach())
238
+ for relative_step in [1e-5, 1e-4]:
239
+ proposal = (
240
+ -source_grad
241
+ * (relative_step * initial.double().norm() / source_grad.double().norm()).float()
242
+ )
243
+ with torch.no_grad():
244
+ parameter.copy_(initial + proposal)
245
+ actual_delta = parameter - initial
246
+ actual_nll = float(engine.ce([encoded])[0]) - nll0
247
+ new_logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1])
248
+ actual_margin = float(new_logits[answer_token] - new_logits[competitor]) - margin0
249
+ predicted_nll = float((grad.double() * actual_delta.double()).sum())
250
+ predicted_margin = float((margin_grad.double() * actual_delta.double()).sum())
251
+ parameter.copy_(initial)
252
+ entry = {
253
+ "case_id": record["case_id"],
254
+ "view_id": view,
255
+ "relative_step": relative_step,
256
+ "competitor_token": competitor,
257
+ "actual_nll_change": actual_nll,
258
+ "predicted_nll_change": predicted_nll,
259
+ "actual_margin_change": actual_margin,
260
+ "predicted_margin_change": predicted_margin,
261
+ }
262
+ for name, actual, predicted in [
263
+ ("nll", actual_nll, predicted_nll),
264
+ ("margin", actual_margin, predicted_margin),
265
+ ]:
266
+ entry[name + "_absolute_error"] = abs(actual - predicted)
267
+ entry[name + "_relative_error"] = abs(actual - predicted) / max(
268
+ abs(predicted), 1e-6
269
+ )
270
+ entry[name + "_sign_match"] = bool(np.sign(actual) == np.sign(predicted))
271
+ rows.append(entry)
272
+ assert torch.equal(parameter, initial)
273
+ write_json(out / "first-order-calibration.json", rows)
274
+
275
+
276
+ def geometry_rows(engine, records):
277
+ encoded = [r["encoded"][v] for r in records for v in range(3)]
278
+ features, originals = [], []
279
+ for start in range(0, len(encoded), 24):
280
+ features.append(engine.features(encoded[start : start + 24]).double().cpu())
281
+ originals.append(engine.original_features.double().cpu())
282
+ phi = torch.cat(features).reshape(len(records), 3, -1)
283
+ unit = F.normalize(phi, dim=-1)
284
+ original = torch.cat(originals).reshape(len(records), 3, -1)
285
+ original_cos = (unit * F.normalize(original, dim=-1)).sum(-1)
286
+ gram = unit[:, 0] @ unit[:, 0].T
287
+ rank = float(gram.trace().square() / gram.square().sum())
288
+ result = {}
289
+ for i, r in enumerate(records):
290
+ others = [
291
+ float(gram[i, j])
292
+ for j, other in enumerate(records)
293
+ if other["target_id"] != r["target_id"]
294
+ ]
295
+ result[r["case_id"]] = {
296
+ "same_fact_cos": float((unit[i, 1:] @ unit[i, 0]).mean()),
297
+ "other_fact_cos": max(others) if others else None,
298
+ "effective_rank": rank,
299
+ "cosine_to_original_phi": float(original_cos[i].mean()),
300
+ "dimension_variance": float(phi[:, 0].var(0, unbiased=False).mean()),
301
+ }
302
+ return result
303
+
304
+
305
+ def evaluate_node(engine, records, keep, texts, step, metadata, out, exposures, full_keep):
306
+ rows = engine.evaluate(records)
307
+ geometry = geometry_rows(engine, records)
308
+ for row in rows:
309
+ row.update(
310
+ metadata,
311
+ step=step,
312
+ exposures=exposures.get(row["case_id"], 0),
313
+ **geometry[row["case_id"]],
314
+ )
315
+ payload = {"rows": rows}
316
+ if full_keep:
317
+ payload["keep"] = engine.evaluate(keep, views=(0,))
318
+ with torch.no_grad():
319
+ text_losses = []
320
+ for i in range(0, len(texts["test"]), 8):
321
+ text_losses.extend(engine.ce(texts["test"][i : i + 8]).tolist())
322
+ payload["text_nll"] = float(np.mean(text_losses))
323
+ payload["text_ppl"] = float(np.exp(payload["text_nll"]))
324
+ write_json(out / f"evaluation-{step:04d}.json", payload)
325
+ return payload
326
+
327
+
328
+ def train_run(
329
+ engine,
330
+ phase,
331
+ records,
332
+ pools,
333
+ texts,
334
+ condition,
335
+ seed,
336
+ episode_id,
337
+ split,
338
+ lr,
339
+ steps,
340
+ run_id,
341
+ lambda_geo=0.0,
342
+ parent_path=None,
343
+ diagnostics=False,
344
+ ):
345
+ cfg = config()
346
+ out = RESULTS / run_id
347
+ out.mkdir(parents=True, exist_ok=True)
348
+ load_parent(engine, parent_path)
349
+ parent_hashes = state_hashes(engine.model)
350
+ parent_hash = aggregate_hash(parent_hashes)
351
+ parameters = engine.configure_trainable(phase)
352
+ trainable = [n for n, p in engine.model.named_parameters() if p.requires_grad]
353
+ meta = {
354
+ "phase": phase,
355
+ "split": split,
356
+ "condition": condition,
357
+ "seed": seed,
358
+ "episode_id": episode_id,
359
+ "parent_hash": parent_hash,
360
+ "parent_path": str(parent_path) if parent_path else None,
361
+ "source_hashes": frozen_training_sources(),
362
+ "config_sha256": sha256(CONFIG_PATH),
363
+ "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
364
+ "trainable_names": trainable,
365
+ "lr": lr,
366
+ "lambda_geo": lambda_geo,
367
+ "steps": steps,
368
+ "case_ids": [r["case_id"] for r in records],
369
+ }
370
+ if (out / "complete.json").exists():
371
+ receipt = read_json(out / "complete.json")
372
+ if receipt["meta"] != meta:
373
+ raise RuntimeError(f"Completed run contract changed: {run_id}")
374
+ return receipt
375
+ engine.make_reference()
376
+ set_determinism(seed)
377
+ random.seed(seed)
378
+ opt = optimizer(parameters, lr)
379
+ write_json(out / "contract.json", meta)
380
+ ledger = {
381
+ "answer_tokens": 0,
382
+ "answer_input_tokens": 0,
383
+ "replay_tokens": 0,
384
+ "replay_input_tokens": 0,
385
+ "geometry_input_tokens": 0,
386
+ "forward_sequences": 0,
387
+ "backward_sequences": 0,
388
+ "optimizer_steps": 0,
389
+ "wall_seconds": 0.0,
390
+ }
391
+ nodes = [n for n in cfg["form" if phase == "form" else "adapt"]["nodes"] if n <= steps]
392
+ if steps not in nodes:
393
+ nodes.append(steps)
394
+ keep = pools["V_keep" if split == "dev" else "U_keep"]
395
+ evaluate_records = pools["V_form"] if phase == "form" and split == "dev" else records
396
+ rng = np.random.default_rng(seed)
397
+ order = rng.permutation(len(records)).tolist() if phase == "form" else list(range(len(records)))
398
+ exposures = {r["case_id"]: 0 for r in records}
399
+ batch_table = []
400
+ for step in range(steps):
401
+ batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)]
402
+ groups = (
403
+ grouping(batch, seed * 100000 + step)
404
+ if condition == "C2"
405
+ else [tuple(range(3 * i, 3 * i + 3)) for i in range(8)]
406
+ )
407
+ batch_table.append({"case_ids": [r["case_id"] for r in batch], "groups": groups})
408
+ write_json(out / "batch-manifest.json", batch_table)
409
+ checkpoints = sorted(out.glob("checkpoint-*.pt"))
410
+ start = 0
411
+ if checkpoints:
412
+ start, ledger = restore_checkpoint(checkpoints[-1], engine, opt, meta)
413
+ for item in batch_table[:start]:
414
+ for case_id in item["case_ids"]:
415
+ exposures[case_id] += 1
416
+ elif diagnostics:
417
+ diagnostic = diagnose_episode(engine, records, replay_batch(pools, texts, 0), lr, out)
418
+ if split == "eval":
419
+ from .hebbian_statistics import predict
420
+
421
+ predictors = read_json(ARTIFACTS / "B-lock.json")["predictors"]
422
+ write_json(
423
+ out / "prospective-predictions.json",
424
+ {
425
+ "saved_at": now(),
426
+ "parent_hash": parent_hash,
427
+ "predictions": [
428
+ {
429
+ "case_id": r["case_id"],
430
+ "values": {
431
+ name: float(predict(model, np.array(r["features"])[None])[0])
432
+ for name, model in predictors.items()
433
+ },
434
+ }
435
+ for r in diagnostic
436
+ ],
437
+ },
438
+ )
439
+ first_order_calibration(engine, min(records, key=lambda r: r["case_id"]), out)
440
+ metadata = {
441
+ k: meta[k] for k in ["phase", "split", "condition", "seed", "episode_id", "parent_hash"]
442
+ }
443
+ if start == 0:
444
+ save_checkpoint(out / "checkpoint-0000.pt", engine, opt, 0, meta, ledger)
445
+ for step in range(start, steps + 1):
446
+ if step in nodes:
447
+ evaluate_node(
448
+ engine,
449
+ evaluate_records,
450
+ keep,
451
+ texts,
452
+ step,
453
+ metadata,
454
+ out,
455
+ exposures,
456
+ full_keep=(phase == "form" or step in [0, 16, 64, 128]),
457
+ )
458
+ if phase == "adapt" and condition.startswith("C") and step in [0, 16, 128]:
459
+ gradients = []
460
+ for r in sorted(records, key=lambda r: r["case_id"])[:4]:
461
+ grads = [engine.gradient(e)[0] for e in r["encoded"]]
462
+ gradients.append(
463
+ {
464
+ "case_id": r["case_id"],
465
+ "p0_p1_gradient_cos": gradient_cos(grads[0], grads[1]),
466
+ "p0_p2_gradient_cos": gradient_cos(grads[0], grads[2]),
467
+ }
468
+ )
469
+ write_json(out / f"gradients-{step:04d}.json", gradients)
470
+ if step in [0, 16, 64, 128, 256]:
471
+ save_checkpoint(out / f"checkpoint-{step:04d}.pt", engine, opt, step, meta, ledger)
472
+ if step == steps:
473
+ break
474
+ batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)]
475
+ encoded = [r["encoded"][v] for r in batch for v in (range(3) if phase == "form" else [0])]
476
+ replay = replay_batch(pools, texts, step)
477
+ torch.cuda.synchronize(engine.device)
478
+ begin = time.monotonic()
479
+ opt.zero_grad(set_to_none=True)
480
+ ce = engine.ce(encoded).mean()
481
+ ce.backward()
482
+ kl = engine.kl(replay).mean()
483
+ kl.backward()
484
+ geo_value, pair_counts = 0.0, None
485
+ if phase == "form":
486
+ features = engine.features(encoded, detach=False)
487
+ targets = [r["target_id"] for r in batch for _ in range(3)]
488
+ geo, pair_counts = contrastive_loss(features, targets, batch_table[step]["groups"])
489
+ if lambda_geo:
490
+ (lambda_geo * geo).backward()
491
+ geo_value = float(geo.detach())
492
+ norm = torch.nn.utils.clip_grad_norm_(parameters, cfg["optimizer"]["clip"])
493
+ opt.step()
494
+ torch.cuda.synchronize(engine.device)
495
+ ledger["wall_seconds"] += time.monotonic() - begin
496
+ ledger["answer_tokens"] += sum(sum(e["loss_mask"]) for e in encoded)
497
+ ledger["answer_input_tokens"] += sum(len(e["input_ids"]) for e in encoded)
498
+ ledger["replay_tokens"] += sum(sum(e["loss_mask"]) for e in replay)
499
+ ledger["replay_input_tokens"] += sum(len(e["input_ids"]) for e in replay)
500
+ if phase == "form":
501
+ ledger["geometry_input_tokens"] += sum(e["answer_start"] for e in encoded)
502
+ ledger["forward_sequences"] += (
503
+ len(encoded) + 2 * len(replay) + (len(encoded) if phase == "form" else 0)
504
+ )
505
+ ledger["backward_sequences"] += (
506
+ len(encoded) + len(replay) + (len(encoded) if lambda_geo else 0)
507
+ )
508
+ ledger["optimizer_steps"] += 1
509
+ for r in batch:
510
+ exposures[r["case_id"]] += 1
511
+ with (out / "training.jsonl").open("a") as f:
512
+ f.write(
513
+ json.dumps(
514
+ {
515
+ "step": step + 1,
516
+ "ce": float(ce.detach()),
517
+ "kl": float(kl.detach()),
518
+ "geo": geo_value,
519
+ "gradient_norm": float(norm),
520
+ "pairs": pair_counts,
521
+ }
522
+ )
523
+ + "\n"
524
+ )
525
+ write_json(
526
+ out / "status.json", {"step": step + 1, "steps": steps, "time": now(), "ledger": ledger}
527
+ )
528
+ if (step + 1) % 16 == 0:
529
+ print(
530
+ run_id,
531
+ step + 1,
532
+ "ce",
533
+ float(ce.detach()),
534
+ "wall",
535
+ ledger["wall_seconds"],
536
+ flush=True,
537
+ )
538
+ final_hashes = state_hashes(engine.model)
539
+ unchanged = all(
540
+ final_hashes[n] == digest for n, digest in parent_hashes.items() if n not in trainable
541
+ )
542
+ assert unchanged, "A parameter outside the intervention scope changed"
543
+ receipt = {
544
+ "meta": meta,
545
+ "completed_at": now(),
546
+ "ledger": ledger,
547
+ "unchanged_outside_scope": unchanged,
548
+ "final_hashes": final_hashes,
549
+ "final_model_hash": aggregate_hash(final_hashes),
550
+ "exposures": exposures,
551
+ "trainable_parameters": sum(p.numel() for p in parameters),
552
+ "estimated_dense_full_backprop_flops_upper_bound": (
553
+ sum(p.numel() for p in engine.model.parameters())
554
+ * (
555
+ 6 * ledger["answer_input_tokens"]
556
+ + 8 * ledger["replay_input_tokens"]
557
+ + (6 if lambda_geo else 2) * ledger["geometry_input_tokens"]
558
+ )
559
+ ),
560
+ }
561
+ write_json(out / "complete.json", receipt)
562
+ return receipt
563
+
564
+
565
+ def run_summary(path):
566
+ evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))]
567
+ nodes = [e["rows"][0]["step"] for e in evaluations]
568
+ rewrite = [
569
+ np.mean([r["answer_em"] for r in e["rows"] if r["view_id"] in [1, 2]]) for e in evaluations
570
+ ]
571
+ keep0 = np.mean([r["answer_em"] for r in evaluations[0]["keep"]])
572
+ keep1 = np.mean([r["answer_em"] for r in evaluations[-1]["keep"]])
573
+ return {
574
+ "q_auc": float(q_auc(rewrite, nodes)),
575
+ "keep_damage": float(keep0 - keep1),
576
+ "answer_nll": float(np.mean([r["answer_nll"] for r in evaluations[-1]["rows"]])),
577
+ }
578
+
579
+
580
+ def select_config(candidates, metric, maximize):
581
+ safe = [
582
+ r for r in candidates if r["keep_damage"] <= config()["statistics"]["keep_damage_reference"]
583
+ ]
584
+ if safe:
585
+ return sorted(safe, key=lambda r: (-1 if maximize else 1) * r[metric])[0]
586
+ return sorted(
587
+ candidates, key=lambda r: (r["keep_damage"], (-1 if maximize else 1) * r[metric])
588
+ )[0]
589
+
590
+
591
+ def preflight(engine, pools, texts):
592
+ records = pools["B_dev"][:8]
593
+ audit = engine.verify_hooks_and_gradients(records[0]["encoded"][0])
594
+ before = state_hashes(engine.model)
595
+ parameters = engine.configure_trainable("adapt")
596
+ engine.make_reference()
597
+ opt = optimizer(parameters, 1e-5)
598
+ torch.cuda.reset_peak_memory_stats(engine.device)
599
+ torch.cuda.synchronize(engine.device)
600
+ start = time.monotonic()
601
+ for step in range(3):
602
+ opt.zero_grad(set_to_none=True)
603
+ engine.ce([r["encoded"][0] for r in records]).mean().backward()
604
+ engine.kl(replay_batch(pools, texts, step)).mean().backward()
605
+ torch.nn.utils.clip_grad_norm_(parameters, 1.0)
606
+ opt.step()
607
+ torch.cuda.synchronize(engine.device)
608
+ seconds = (time.monotonic() - start) / 3
609
+ engine.restore_base()
610
+ assert before == state_hashes(engine.model)
611
+ estimate = {
612
+ "time": now(),
613
+ "device": str(engine.device),
614
+ "adapt_step_seconds": seconds,
615
+ "peak_memory_bytes": torch.cuda.max_memory_allocated(engine.device),
616
+ "formal_adapt_steps": 11264,
617
+ "formal_adapt_gpu_hours": seconds * 11264 / 3600,
618
+ "formation_estimate_factor": 3,
619
+ "formal_formation_gpu_hours_estimate": seconds * 3 * 2304 / 3600,
620
+ "excludes": [
621
+ "generation and NLL evaluation",
622
+ "gradient diagnostics",
623
+ "development",
624
+ "disk IO",
625
+ ],
626
+ "microbatch_answer": 8,
627
+ "microbatch_replay": 8,
628
+ "reference_parent_restored": True,
629
+ }
630
+ write_json(ARTIFACTS / "estimate.json", estimate)
631
+ write_json(ARTIFACTS / "qwen-interface-audit.json", audit)
632
+ print(estimate, flush=True)
633
+
634
+
635
+ def dispatch(args):
636
+ if not (ARTIFACTS / "data-lock.json").exists():
637
+ raise RuntimeError("data-lock is required before development or evaluation")
638
+ data_lock = read_json(ARTIFACTS / "data-lock.json")
639
+ for name, digest in data_lock["files"].items():
640
+ if sha256(DATA / name) != digest:
641
+ raise RuntimeError(f"Frozen data changed: {name}")
642
+ if not read_json(ARTIFACTS / "A/audit.json")["pass"]:
643
+ raise RuntimeError("Stage A must pass before model training")
644
+ pools = read_json(DATA / "pools.json")
645
+ texts = read_json(DATA / "text.json")
646
+ episodes = read_json(DATA / "episodes.json")
647
+ by_id = {r["case_id"]: r for rows in pools.values() for r in rows}
648
+ engine = QwenExperiment(args.device)
649
+ if args.command == "preflight":
650
+ return preflight(engine, pools, texts)
651
+ if args.command == "diagnose":
652
+ if args.split == "dev":
653
+ learning_rates = config()["adapt"]["learning_rates"]
654
+ else:
655
+ learning_rates = [read_json(ARTIFACTS / "B-lock.json")["learning_rate"]]
656
+ tasks = list(itertools.product(learning_rates, enumerate(episodes["B_" + args.split])))
657
+ for lr, (episode, ids) in tasks[args.shard :: args.shards]:
658
+ run_id = f"B/{args.split}-lr{lr:g}-e{episode}"
659
+ train_run(
660
+ engine,
661
+ "adapt",
662
+ [by_id[i] for i in ids],
663
+ pools,
664
+ texts,
665
+ "B",
666
+ 0,
667
+ episode,
668
+ args.split,
669
+ lr,
670
+ 128,
671
+ run_id,
672
+ diagnostics=True,
673
+ )
674
+ return
675
+ b_lr = read_json(ARTIFACTS / "B-lock.json")["learning_rate"]
676
+ if args.command == "form" and args.split == "dev":
677
+ candidates = []
678
+ for lr in config()["form"]["learning_rates"]:
679
+ run_id = f"C/dev-C0-lr{lr:g}"
680
+ train_run(
681
+ engine, "form", pools["F_form"], pools, texts, "C0", 10, -1, "dev", lr, 256, run_id
682
+ )
683
+ candidates.append(
684
+ {"learning_rate": lr, "run_id": run_id, **run_summary(RESULTS / run_id)}
685
+ )
686
+ chosen = select_config(candidates, "answer_nll", False)
687
+ lr = chosen["learning_rate"]
688
+ formation_candidates = [{"condition": "C0", "lambda_geo": 0.0, **chosen}]
689
+ for lam in config()["form"]["lambdas"]:
690
+ run_id = f"C/dev-C1-lambda{lam:g}"
691
+ train_run(
692
+ engine,
693
+ "form",
694
+ pools["F_form"],
695
+ pools,
696
+ texts,
697
+ "C1",
698
+ 10,
699
+ -1,
700
+ "dev",
701
+ lr,
702
+ 256,
703
+ run_id,
704
+ lambda_geo=lam,
705
+ )
706
+ formation_candidates.append(
707
+ {
708
+ "condition": "C1",
709
+ "lambda_geo": lam,
710
+ "run_id": run_id,
711
+ **run_summary(RESULTS / run_id),
712
+ }
713
+ )
714
+ for item in formation_candidates:
715
+ adapt_results = []
716
+ for episode, ids in enumerate(episodes["C_dev"]):
717
+ run_id = f"C/adapt-dev-{item['condition']}-lambda{item['lambda_geo']:g}-e{episode}"
718
+ train_run(
719
+ engine,
720
+ "adapt",
721
+ [by_id[i] for i in ids],
722
+ pools,
723
+ texts,
724
+ item["condition"],
725
+ 10,
726
+ episode,
727
+ "dev",
728
+ b_lr,
729
+ 64,
730
+ run_id,
731
+ parent_path=RESULTS / item["run_id"] / "checkpoint-0256.pt",
732
+ )
733
+ adapt_results.append(run_summary(RESULTS / run_id))
734
+ item["future_q_auc"] = float(np.mean([r["q_auc"] for r in adapt_results]))
735
+ item["adapt_results"] = adapt_results
736
+ best = select_config(
737
+ [r for r in formation_candidates if r["condition"] == "C1"], "future_q_auc", True
738
+ )
739
+ lam = best["lambda_geo"]
740
+ train_run(
741
+ engine,
742
+ "form",
743
+ pools["F_form"],
744
+ pools,
745
+ texts,
746
+ "C2",
747
+ 10,
748
+ -1,
749
+ "dev",
750
+ lr,
751
+ 256,
752
+ "C/dev-C2-engineering",
753
+ lambda_geo=lam,
754
+ )
755
+ write_json(
756
+ ARTIFACTS / "C-lock.json",
757
+ {
758
+ "time": now(),
759
+ "learning_rate": lr,
760
+ "lambda_geo": lam,
761
+ "adapt_learning_rate": b_lr,
762
+ "lr_candidates": candidates,
763
+ "formation_candidates": formation_candidates,
764
+ "source_hashes": frozen_training_sources(),
765
+ "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
766
+ "seeds": [0, 1, 2],
767
+ "conditions": ["C0", "C1", "C2"],
768
+ "episodes": episodes["C_eval"],
769
+ "status": "locked",
770
+ },
771
+ )
772
+ return
773
+ c_lock = read_json(ARTIFACTS / "C-lock.json")
774
+ if args.command == "form":
775
+ tasks = list(itertools.product(["C0", "C1", "C2"], [0, 1, 2]))
776
+ for condition, seed in tasks[args.shard :: args.shards]:
777
+ train_run(
778
+ engine,
779
+ "form",
780
+ pools["F_form"],
781
+ pools,
782
+ texts,
783
+ condition,
784
+ seed,
785
+ -1,
786
+ "eval",
787
+ c_lock["learning_rate"],
788
+ 256,
789
+ f"C/form-{condition}-s{seed}",
790
+ lambda_geo=0.0 if condition == "C0" else c_lock["lambda_geo"],
791
+ )
792
+ elif args.command == "adapt":
793
+ tasks = list(
794
+ itertools.product(["C0", "C1", "C2"], [0, 1, 2], enumerate(episodes["C_eval"]))
795
+ )
796
+ for condition, seed, (episode, ids) in tasks[args.shard :: args.shards]:
797
+ train_run(
798
+ engine,
799
+ "adapt",
800
+ [by_id[i] for i in ids],
801
+ pools,
802
+ texts,
803
+ condition,
804
+ seed,
805
+ episode,
806
+ "eval",
807
+ b_lr,
808
+ 128,
809
+ f"C/adapt-{condition}-s{seed}-e{episode}",
810
+ parent_path=RESULTS / f"C/form-{condition}-s{seed}/checkpoint-0256.pt",
811
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/independent_alignment.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replicate the existing state objective in two ordinary, independent GPT layers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch.nn import functional as F
11
+
12
+ from . import representation_alignment as original
13
+ from .grok_depth import write_json
14
+ from .latent_scaling import build_world, model_digest
15
+ from .storage_composition import data_digest, evaluate, file_hash
16
+
17
+
18
+ def validate_model(spec, model):
19
+ if spec["layers"] != 2 or spec["repeats"] != 1:
20
+ raise ValueError("This replication requires two independent layers, executed once")
21
+ blocks = list(model.iter_blocks())
22
+ assert len(blocks) == 2 and blocks[0] is not blocks[1]
23
+ assert not {p.data_ptr() for p in blocks[0].parameters()} & {
24
+ p.data_ptr() for p in blocks[1].parameters()
25
+ }
26
+ assert all(p.requires_grad for p in model.parameters())
27
+
28
+
29
+ @torch.no_grad()
30
+ def diagnose(model, world, device):
31
+ """Original readout of a pure first-hop prefix; no fitted probe or final answer."""
32
+ model.eval()
33
+ metrics, predictions = {}, {}
34
+ for task in ("common_atomic", "familiar_test", "strict_test"):
35
+ rows = world[task]
36
+ prefixes = np.column_stack(
37
+ (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1])
38
+ )
39
+ labels = rows[:, 2]
40
+ guesses, cosines = [], []
41
+ for start in range(0, len(rows), 256):
42
+ tokens = torch.as_tensor(prefixes[start : start + 256], device=device)
43
+ targets = torch.as_tensor(labels[start : start + 256], device=device)
44
+ _, state = model(tokens, return_bridge=True)
45
+ logits = F.linear(model.ln_final(state), model.token.weight)
46
+ guesses.append(logits.argmax(-1).cpu().numpy())
47
+ cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy())
48
+ guess, cosine = np.concatenate(guesses), np.concatenate(cosines)
49
+ correct = guess == labels
50
+ metrics[task] = dict(
51
+ n=len(rows),
52
+ first_hop_original_readout_accuracy=float(correct.mean()),
53
+ mean_cosine_to_input_embedding=float(cosine.mean()),
54
+ pure_prefix=True,
55
+ )
56
+ predictions.update(
57
+ {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine}
58
+ )
59
+ return metrics, predictions
60
+
61
+
62
+ def train(spec, out, source, device):
63
+ model = original.new_model(spec, "cpu")
64
+ validate_model(spec, model)
65
+ assert model_digest(model) == spec["initial_model_sha256"]
66
+ assert data_digest(build_world(spec)) == spec["data_sha256"]
67
+ del model
68
+ # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact.
69
+ original.train(spec, out, source, device)
70
+ out = Path(out)
71
+ payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False)
72
+ model = original.new_model(spec, device)
73
+ model.load_state_dict(payload["model"])
74
+ metrics, predictions = diagnose(model, build_world(spec), device)
75
+ write_json(out / "state-diagnostics.json", metrics)
76
+ np.savez_compressed(out / "state-predictions.npz", **predictions)
77
+
78
+
79
+ def audit(out, device):
80
+ """Independent process reload of full generation and original intermediate readout."""
81
+ out = Path(out)
82
+ torch.set_num_threads(1)
83
+ torch.set_num_interop_threads(1)
84
+ torch.backends.cuda.matmul.allow_tf32 = True
85
+ torch.backends.cudnn.allow_tf32 = True
86
+ payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False)
87
+ spec = payload["spec"]
88
+ model = original.new_model(spec, device)
89
+ validate_model(spec, model)
90
+ model.load_state_dict(payload["model"])
91
+ world = build_world(spec)
92
+ stored_world = np.load(out / "world.npz")
93
+ for key, value in world.items():
94
+ np.testing.assert_array_equal(value, stored_world[key])
95
+ assert data_digest(world) == spec["data_sha256"]
96
+ complete = json.loads((out / "complete.json").read_text())
97
+ assert file_hash(out / "model.pt") == complete["model_sha256"]
98
+ metrics, predictions = evaluate(model, world, "low", device)
99
+ saved = np.load(out / f"predictions-{spec['steps']:06d}.npz")
100
+ maximum = 0.0
101
+ for key, value in predictions.items():
102
+ if key.endswith("nll"):
103
+ maximum = max(maximum, float(np.max(np.abs(value - saved[key]))))
104
+ np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5)
105
+ else:
106
+ np.testing.assert_array_equal(value, saved[key])
107
+ state_metrics, state_predictions = diagnose(model, world, device)
108
+ saved_state = np.load(out / "state-predictions.npz")
109
+ for key, value in state_predictions.items():
110
+ if key.endswith("cosine"):
111
+ np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5)
112
+ else:
113
+ np.testing.assert_array_equal(value, saved_state[key])
114
+ write_json(
115
+ out / "audit.json",
116
+ dict(
117
+ passed=True,
118
+ metrics=metrics,
119
+ state_metrics=state_metrics,
120
+ max_nll_error=maximum,
121
+ allow_tf32=True,
122
+ independent_parameters=True,
123
+ ),
124
+ )
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_editing.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local factual updates and downstream composition in existing aligned GPTs.
2
+
3
+ Cases are selected from the graph alone, before loading any model predictions.
4
+ Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent
5
+ replay reference. No composition labels or intermediate-state targets enter
6
+ optimization. Finite replay KL is a regularizer, not exact preservation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import time
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch.nn import functional as F
21
+
22
+ from .grok_depth import utc, write_json
23
+ from .latent_scaling import build_world, model_digest
24
+ from .representation_alignment import new_model
25
+ from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences
26
+
27
+ ROLES = ("first", "second")
28
+ STRATA = ("familiar", "strict")
29
+ DEFAULT_NODES = (0, 32, 128, 512)
30
+
31
+
32
+ def _rows(values, width):
33
+ return np.asarray(values, dtype=np.int64).reshape(-1, width)
34
+
35
+
36
+ def _unique(values, width):
37
+ return _rows(sorted(set(map(tuple, _rows(values, width)))), width)
38
+
39
+
40
+ def _hash_json(value):
41
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
42
+
43
+
44
+ def _batch_hash(batch):
45
+ digest = hashlib.sha256()
46
+ for tensor in batch:
47
+ array = tensor.detach().cpu().numpy()
48
+ digest.update(str(array.dtype).encode())
49
+ digest.update(str(array.shape).encode())
50
+ digest.update(array.tobytes())
51
+ return digest.hexdigest()
52
+
53
+
54
+ def learned_atoms(world):
55
+ """Only atomics actually supervised in the representation parent."""
56
+ return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3)
57
+
58
+
59
+ def composition_pools(world):
60
+ """All legal untrained queries, plus the original holdout and training sets."""
61
+ trained = set(map(tuple, world["train_composite"]))
62
+ full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5)
63
+ familiar = _rows([r for r in full if tuple(r) not in trained], 5)
64
+ return {
65
+ "familiar": familiar,
66
+ "strict": world["strict_test"].copy(),
67
+ "registered_familiar": world["familiar_test"].copy(),
68
+ "train": world["train_composite"].copy(),
69
+ }
70
+
71
+
72
+ def affected(rows, fact, role):
73
+ """Whether a query uses this factual address, independently of its answer."""
74
+ columns = (0, 1) if role == "first" else (2, 3)
75
+ return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1])
76
+
77
+
78
+ def rewrite(rows, old_fact, new_fact, role, lookup):
79
+ result = rows.copy()
80
+ mask = affected(rows, old_fact, role)
81
+ if role == "first":
82
+ result[mask, 2] = new_fact[2]
83
+ for index in np.flatnonzero(mask):
84
+ result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])]
85
+ else:
86
+ result[mask, 4] = new_fact[2]
87
+ return result
88
+
89
+
90
+ def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32):
91
+ """Return JSON-compatible selected cases and graph-only eligibility counts.
92
+
93
+ Each distinct atomic address receives at most one counterfactual per role.
94
+ First-hop replacements stay in the original familiar/strict bridge group and
95
+ change at least one affected untrained composition answer. Strict cases never
96
+ borrow a bridge with composition experience from the familiar group.
97
+ """
98
+ if per_cell < 1 or replay_n < 1:
99
+ raise ValueError("Positive case and replay counts are required")
100
+ world = build_world(parent_spec)
101
+ atoms = learned_atoms(world)
102
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
103
+ pools = composition_pools(world)
104
+ rng = np.random.default_rng(seed + int(parent_spec["world"]))
105
+ candidates, qualification = [], {}
106
+ for role in ROLES:
107
+ for stratum in STRATA:
108
+ rows = pools[stratum]
109
+ addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3)
110
+ bridges = np.unique(rows[:, 2])
111
+ # Include all trained bridges in that group, even if the holdout
112
+ # happens not to visit them (strict rows enumerate all chains).
113
+ group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"]
114
+ group_bridges = np.unique(group[group[:, 1] >= 17, 0])
115
+ if stratum == "strict":
116
+ familiar_bridges = world["background_atomic"]
117
+ familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0]
118
+ group_bridges = np.setdiff1d(group_bridges, familiar_bridges)
119
+ bridges = np.union1d(bridges, group_bridges)
120
+ tails = np.unique(atoms[atoms[:, 1] >= 17, 2])
121
+ eligible, replacement_count = [], 0
122
+ for old in addresses:
123
+ impacted = rows[affected(rows, old, role)]
124
+ choices = []
125
+ for value in bridges if role == "first" else tails:
126
+ if value == old[2]:
127
+ continue
128
+ new = [int(old[0]), int(old[1]), int(value)]
129
+ updated = rewrite(impacted, old, new, role, lookup)
130
+ if np.any(updated[:, -1] != impacted[:, -1]):
131
+ choices.append(new)
132
+ replacement_count += len(choices)
133
+ if choices:
134
+ eligible.append((old.tolist(), choices))
135
+ key = f"{role}_{stratum}"
136
+ qualification[key] = {
137
+ "candidate_addresses": len(addresses),
138
+ "eligible_addresses": len(eligible),
139
+ "eligible_replacements": replacement_count,
140
+ "untrained_queries": len(rows),
141
+ }
142
+ if len(eligible) < per_cell:
143
+ raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}")
144
+ order = rng.permutation(len(eligible))[:per_cell]
145
+ for serial, index in enumerate(order):
146
+ old, choices = eligible[index]
147
+ new = choices[int(rng.integers(len(choices)))]
148
+ candidates.append(
149
+ {
150
+ "case_id": f"{key}-{serial:02d}",
151
+ "role": role,
152
+ "stratum": stratum,
153
+ "old_fact": old,
154
+ "new_fact": new,
155
+ }
156
+ )
157
+ for case in candidates:
158
+ tasks, originals = case_tasks(world, case, replay_indices=None)
159
+ necessary = set(map(tuple, tasks["necessary_atomic"]))
160
+ allowed = [
161
+ i
162
+ for i, row in enumerate(atoms)
163
+ if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary
164
+ ]
165
+ if len(allowed) < replay_n:
166
+ raise ValueError("Insufficient independent replay atomics")
167
+ case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False)))
168
+ case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()}
169
+ return candidates, qualification
170
+
171
+
172
+ def case_tasks(world, case, replay_indices=None):
173
+ """Construct E/R/U/D with address-based exclusions and recomputed truth."""
174
+ atoms = learned_atoms(world)
175
+ lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
176
+ old, new, role = case["old_fact"], case["new_fact"], case["role"]
177
+ if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]:
178
+ raise ValueError("An edit must replace one existing factual value")
179
+ tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)}
180
+ originals, necessary = {}, []
181
+ for stratum, rows in composition_pools(world).items():
182
+ mask = affected(rows, old, role)
183
+ tasks[f"U_{stratum}"] = rows[~mask].copy()
184
+ old_rows = rows[mask].copy()
185
+ new_rows = rewrite(old_rows, old, new, role, lookup)
186
+ changed = old_rows[:, -1] != new_rows[:, -1]
187
+ if stratum == "train":
188
+ # Training-query transfer is reported separately from held-out D.
189
+ name = f"T_{role}_train"
190
+ originals[name] = old_rows
191
+ tasks[name] = new_rows
192
+ else:
193
+ name = f"D_{role}_{stratum}"
194
+ originals[name] = old_rows[changed]
195
+ tasks[name] = new_rows[changed]
196
+ same = f"S_same_answer_{role}_{stratum}"
197
+ originals[same] = old_rows[~changed]
198
+ tasks[same] = new_rows[~changed]
199
+ if stratum in STRATA:
200
+ for h, r1, b, r2, t in tasks[name]:
201
+ prerequisite = (b, r2, t) if role == "first" else (h, r1, b)
202
+ necessary.append(prerequisite)
203
+ tasks["necessary_atomic"] = _unique(necessary, 3)
204
+ replay = case.get("replay_indices", []) if replay_indices is None else replay_indices
205
+ if len(set(replay)) != len(replay):
206
+ raise ValueError("Replay indices must be unique")
207
+ target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1))
208
+ if len(target) != 1 or int(target[0]) in replay:
209
+ raise ValueError("Replay cannot contain the edited address")
210
+ tasks["R_atomic"] = atoms[replay].copy()
211
+ tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0)
212
+ return tasks, originals
213
+
214
+
215
+ def answer_batch(rows, device):
216
+ """Only answer, punctuation and EOS labels; no prefix or bridge labels."""
217
+ tokens, labels = pack_sentences(_rows(rows, 3))
218
+ positions = np.tile([4, 5, 6], (len(rows), 1))
219
+ targets = labels[np.arange(len(rows))[:, None], positions]
220
+ expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))])
221
+ np.testing.assert_array_equal(targets, expected)
222
+ return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets))
223
+
224
+
225
+ def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0):
226
+ target = model(target_batch[0], positions=target_batch[1])
227
+ ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten())
228
+ replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1)
229
+ if parent_log.requires_grad:
230
+ raise ValueError("Replay reference must be detached")
231
+ kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean()
232
+ return ce + replay_weight * kl, ce, kl
233
+
234
+
235
+ def _generate(model, rows, device, batch_size):
236
+ if len(rows):
237
+ return generate_rows(model, rows, device, batch_size=batch_size)
238
+ return (
239
+ {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None},
240
+ {
241
+ "generated": np.empty((0, 3), dtype=np.int64),
242
+ "correct": np.empty(0, dtype=bool),
243
+ "answer_nll": np.empty(0),
244
+ },
245
+ )
246
+
247
+
248
+ def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512):
249
+ """Full-pool scores and separately labelled prerequisite/parent subsets."""
250
+ metrics, raw = {}, {}
251
+ for name, rows in tasks.items():
252
+ values, predictions = _generate(model, rows, device, batch_size)
253
+ raw.update({f"{name}__{k}": v for k, v in predictions.items()})
254
+ if name in originals:
255
+ old = originals[name]
256
+ generated = predictions["generated"]
257
+ changed = old[:, -1] != rows[:, -1]
258
+ old_correct = (generated[:, 0] == old[:, -1]) & np.all(
259
+ generated[:, 1:] == [5, 1], axis=1
260
+ )
261
+ prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]]
262
+ _m, needed = _generate(model, prerequisite, device, batch_size)
263
+ edited_ok = metrics["E_new"]["accuracy"] == 1.0
264
+ covered = needed["correct"] & edited_ok
265
+ baseline = parent_correct[name]
266
+ valid_parent = baseline & changed
267
+ correct = predictions["correct"]
268
+ values.update(
269
+ {
270
+ "changed_answer_n": int(changed.sum()),
271
+ "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None,
272
+ "parent_correct_n": int(baseline.sum()),
273
+ "parent_correct_coverage": float(baseline.mean()) if len(rows) else None,
274
+ "new_following_parent_correct": float(correct[valid_parent].mean())
275
+ if valid_parent.any()
276
+ else None,
277
+ "old_retained_parent_correct": float(old_correct[valid_parent].mean())
278
+ if valid_parent.any()
279
+ else None,
280
+ "direct_edit_success": edited_ok,
281
+ "necessary_atomic_correct_n": int(needed["correct"].sum()),
282
+ "operation_correct_n": int(covered.sum()),
283
+ "operation_correct_coverage": float(covered.mean()) if len(rows) else None,
284
+ "new_following_operation_correct": float(correct[covered].mean())
285
+ if covered.any()
286
+ else None,
287
+ }
288
+ )
289
+ raw[f"{name}__parent_correct"] = baseline
290
+ raw[f"{name}__operation_correct"] = covered
291
+ raw[f"{name}__old_correct"] = old_correct
292
+ raw[f"{name}__necessary_generated"] = needed["generated"]
293
+ raw[f"{name}__new_rows"] = rows
294
+ raw[f"{name}__old_rows"] = old
295
+ metrics[name] = values
296
+ return metrics, raw
297
+
298
+
299
+ def editable_parameters(model, scope="mlp", block_index=0):
300
+ prefix = f"blocks.{block_index}.mlp."
301
+ selected = [
302
+ name
303
+ for name, _ in model.named_parameters()
304
+ if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight")
305
+ ]
306
+ if scope not in {"mlp", "down"} or not selected:
307
+ raise ValueError("Unknown or empty local parameter scope")
308
+ for name, parameter in model.named_parameters():
309
+ parameter.requires_grad_(name in selected)
310
+ parameter.grad = None
311
+ return selected
312
+
313
+
314
+ def _configure(device):
315
+ device = torch.device(device)
316
+ torch.set_num_threads(1)
317
+ torch.backends.cuda.matmul.allow_tf32 = True
318
+ torch.backends.cudnn.allow_tf32 = True
319
+ if device.type == "cuda":
320
+ torch.cuda.set_device(device)
321
+ return device
322
+
323
+
324
+ def _load_parent(parent_dir, device):
325
+ path = Path(parent_dir) / "model.pt"
326
+ payload = torch.load(path, map_location="cpu", weights_only=False)
327
+ model = new_model(payload["spec"], device).eval()
328
+ model.load_state_dict(payload["model"])
329
+ world = build_world(payload["spec"])
330
+ if (Path(parent_dir) / "world.npz").exists():
331
+ with np.load(Path(parent_dir) / "world.npz") as saved:
332
+ for name, rows in world.items():
333
+ np.testing.assert_array_equal(rows, saved[name])
334
+ return model, world, payload["spec"]
335
+
336
+
337
+ def _parent_masks(parent, originals, device, batch_size):
338
+ return {
339
+ name: _generate(parent, rows, device, batch_size)[1]["correct"]
340
+ for name, rows in originals.items()
341
+ }
342
+
343
+
344
+ def run(spec, out, device="cuda:0"):
345
+ """Execute one parent, a graph-selected case set and optional development lr grid.
346
+
347
+ The caller owns source freezing, resource allocation and W&B startup. Each
348
+ branch has run/learning/complete artifacts. Root ``step`` is a strictly
349
+ increasing evaluation index, including every branch's unchanged node zero;
350
+ ``optimizer_updates`` separately records cumulative optimization work.
351
+ Target labels and replay KL positions have separate exposure counters.
352
+ ``status.json`` retains completed-branch progress, explicitly labelled in
353
+ the manifest; it does not define the tracking series' step axis.
354
+ """
355
+ device = _configure(device)
356
+ out = Path(out)
357
+ out.mkdir(parents=True, exist_ok=True)
358
+ if (out / "run.json").exists() or (out / "complete.json").exists():
359
+ raise FileExistsError(f"Do not overwrite an existing attempt: {out}")
360
+ nodes = spec.get("nodes", list(DEFAULT_NODES))
361
+ if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0:
362
+ raise ValueError("Nodes must increase from zero to a positive fixed endpoint")
363
+ rates = spec.get("learning_rates", [spec.get("lr", 1e-4)])
364
+ if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates):
365
+ raise ValueError("Learning rates must be positive and unique")
366
+ if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1:
367
+ raise ValueError("Learning-rate grids are development-only")
368
+ arms = spec.get("arms", ["edit", "sham"])
369
+ if sorted(arms) != ["edit", "sham"]:
370
+ raise ValueError("Every case requires paired edit and sham branches")
371
+ parent, world, parent_spec = _load_parent(spec["parent_dir"], device)
372
+ parent_hash = model_digest(parent)
373
+ cases, qualification = graph_cases(
374
+ parent_spec,
375
+ seed=spec.get("candidate_seed", 780011),
376
+ per_cell=spec.get("per_cell", 2),
377
+ replay_n=spec.get("replay_n", 32),
378
+ )
379
+ if "case_ids" in spec:
380
+ requested = set(spec["case_ids"])
381
+ if not requested or not requested <= {c["case_id"] for c in cases}:
382
+ raise ValueError("Unknown/empty fixed graph-selected case subset")
383
+ cases = [c for c in cases if c["case_id"] in requested]
384
+ manifest = {
385
+ "spec": spec,
386
+ "parent_spec": parent_spec,
387
+ "cases": cases,
388
+ "qualification": qualification,
389
+ "case_sha256": _hash_json(cases),
390
+ "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"),
391
+ "parent_model_sha256": parent_hash,
392
+ "world_sha256": data_digest(world),
393
+ "created_utc": utc(),
394
+ "dtype": "float32",
395
+ "allow_tf32": True,
396
+ "pid": os.getpid(),
397
+ "gpu": device.index if device.type == "cuda" else None,
398
+ "branches": len(cases) * len(rates) * len(arms),
399
+ "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1],
400
+ "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes),
401
+ "learning_step_unit": "evaluation_index",
402
+ "status_step_unit": "completed_branches",
403
+ "scope_warning": "The selected MLP is shared across all repeated executions",
404
+ }
405
+ write_json(out / "run.json", manifest)
406
+ write_json(out / "cases.json", cases)
407
+ np.savez_compressed(out / "world.npz", **world)
408
+ root_learning, branch_summaries, completed_steps = [], [], 0
409
+ started = time.perf_counter()
410
+ training_seconds = 0.0
411
+ batch_size = spec.get("eval_batch_size", 512)
412
+ for case in cases:
413
+ tasks, originals = case_tasks(world, case)
414
+ parent_correct = _parent_masks(parent, originals, device, batch_size)
415
+ parent_metrics, parent_predictions = evaluate_case(
416
+ parent,
417
+ tasks,
418
+ originals,
419
+ parent_correct,
420
+ case["role"],
421
+ device,
422
+ batch_size,
423
+ )
424
+ case_out = out / case["case_id"]
425
+ case_out.mkdir()
426
+ np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions)
427
+ write_json(case_out / "parent-metrics.json", parent_metrics)
428
+ np.savez_compressed(case_out / "tasks.npz", **tasks)
429
+ replay_batch = answer_batch(tasks["R_atomic"], device)
430
+ with torch.no_grad():
431
+ parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach()
432
+ for lr in rates:
433
+ for arm in arms:
434
+ branch_name = f"lr{lr:.8g}-{arm}"
435
+ branch_out = case_out / branch_name
436
+ branch_out.mkdir()
437
+ model = copy.deepcopy(parent).eval()
438
+ selected = editable_parameters(
439
+ model,
440
+ spec.get("parameter_scope", "mlp"),
441
+ spec.get("block_index", 0),
442
+ )
443
+ parameters = dict(model.named_parameters())
444
+ optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr)
445
+ target = tasks["E_new" if arm == "edit" else "E_old"]
446
+ target_batch = answer_batch(target, device)
447
+ write_json(
448
+ branch_out / "run.json",
449
+ {
450
+ "case_id": case["case_id"],
451
+ "arm": arm,
452
+ "lr": lr,
453
+ "parent_model_sha256": parent_hash,
454
+ "editable_parameters": selected,
455
+ "optimizer": "Adam, fresh state, zero weight decay",
456
+ "sampling": "same fixed full replay batch on every update; no dropout",
457
+ "old_fact_sha256": _hash_json(case["old_fact"]),
458
+ "new_fact_sha256": _hash_json(case["new_fact"]),
459
+ "target_batch_sha256": _batch_hash(target_batch),
460
+ "replay_batch_sha256": _batch_hash(replay_batch),
461
+ "parent_reference_sha256": _batch_hash((parent_log,)),
462
+ "nodes": nodes,
463
+ },
464
+ )
465
+ np.savez_compressed(
466
+ branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy()
467
+ )
468
+ step, losses, history = 0, [], []
469
+ for node in nodes:
470
+ if device.type == "cuda":
471
+ torch.cuda.synchronize(device)
472
+ began = time.perf_counter()
473
+ while step < node:
474
+ optimizer.zero_grad(set_to_none=True)
475
+ loss, ce, kl = edit_objective(
476
+ model,
477
+ target_batch,
478
+ replay_batch,
479
+ parent_log,
480
+ spec.get("replay_weight", 1.0),
481
+ )
482
+ if not torch.isfinite(loss):
483
+ raise FloatingPointError(f"Nonfinite edit loss at {step}")
484
+ loss.backward()
485
+ gradient_norm = torch.nn.utils.clip_grad_norm_(
486
+ [parameters[n] for n in selected],
487
+ spec.get("clip_norm", 1.0),
488
+ )
489
+ optimizer.step()
490
+ step += 1
491
+ losses.append(
492
+ {
493
+ "step": step,
494
+ "loss": float(loss.detach()),
495
+ "target_ce": float(ce.detach()),
496
+ "replay_kl": float(kl.detach()),
497
+ "gradient_norm": float(gradient_norm),
498
+ }
499
+ )
500
+ if device.type == "cuda":
501
+ torch.cuda.synchronize(device)
502
+ training_seconds += time.perf_counter() - began
503
+ metrics, predictions = evaluate_case(
504
+ model,
505
+ tasks,
506
+ originals,
507
+ parent_correct,
508
+ case["role"],
509
+ device,
510
+ batch_size,
511
+ )
512
+ current_hash = model_digest(model)
513
+ record = {
514
+ "step": step,
515
+ "metrics": metrics,
516
+ "model_sha256": current_hash,
517
+ "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"]
518
+ == 1,
519
+ "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95,
520
+ "loss": losses[-1] if losses else None,
521
+ }
522
+ history.append(record)
523
+ write_json(branch_out / "learning.json", history)
524
+ write_json(branch_out / "losses.json", losses)
525
+ np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions)
526
+ torch.save(
527
+ {
528
+ "edited_tensors": {
529
+ n: parameters[n].detach().cpu().clone() for n in selected
530
+ },
531
+ "model_sha256": current_hash,
532
+ "step": step,
533
+ },
534
+ branch_out / f"tensors-{step:06d}.pt",
535
+ )
536
+ root_learning.append(
537
+ {
538
+ "step": len(root_learning),
539
+ "branch_step": step,
540
+ "completed_branches": len(branch_summaries) + int(step == nodes[-1]),
541
+ "optimizer_updates": completed_steps + step,
542
+ "case_id": case["case_id"],
543
+ "arm": arm,
544
+ "lr": lr,
545
+ "metrics": metrics,
546
+ "training_seconds": training_seconds,
547
+ "wall_seconds": time.perf_counter() - started,
548
+ "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])),
549
+ "target_supervised_tokens": (completed_steps + step) * 3,
550
+ "replay_distillation_positions": (completed_steps + step)
551
+ * len(tasks["R_atomic"])
552
+ * 3,
553
+ }
554
+ )
555
+ write_json(out / "learning.json", root_learning)
556
+ write_json(
557
+ out / "status.json",
558
+ {
559
+ "state": "running",
560
+ "step": len(branch_summaries),
561
+ "optimizer_updates": completed_steps + step,
562
+ "budget": manifest["branches"],
563
+ "case_id": case["case_id"],
564
+ "arm": arm,
565
+ "lr": lr,
566
+ },
567
+ )
568
+ changed = [
569
+ n
570
+ for n, t in model.state_dict().items()
571
+ if not torch.equal(t, parent.state_dict()[n])
572
+ ]
573
+ if set(changed) - set(selected) or model_digest(parent) != parent_hash:
574
+ raise AssertionError("A frozen parameter or the parent changed")
575
+ complete = {
576
+ "case_id": case["case_id"],
577
+ "role": case["role"],
578
+ "stratum": case["stratum"],
579
+ "lr": lr,
580
+ "arm": arm,
581
+ "path": str(branch_out.relative_to(out)),
582
+ "metrics": metrics,
583
+ "steps": step,
584
+ "changed_tensors": changed,
585
+ "parent_model_sha256": parent_hash,
586
+ "final_model_sha256": current_hash,
587
+ "delta_l2": float(
588
+ torch.sqrt(
589
+ sum(
590
+ (parameters[n] - dict(parent.named_parameters())[n]).square().sum()
591
+ for n in selected
592
+ )
593
+ ).detach()
594
+ ),
595
+ "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"),
596
+ }
597
+ write_json(branch_out / "complete.json", complete)
598
+ branch_summaries.append(complete)
599
+ completed_steps += step
600
+ result = {
601
+ "status": "complete",
602
+ "branches": branch_summaries,
603
+ "updates": completed_steps,
604
+ "training_seconds": training_seconds,
605
+ "wall_seconds": time.perf_counter() - started,
606
+ "finished_utc": utc(),
607
+ "case_sha256": manifest["case_sha256"],
608
+ }
609
+ write_json(out / "complete.json", result)
610
+ write_json(
611
+ out / "status.json",
612
+ {
613
+ "state": "complete",
614
+ "step": len(branch_summaries),
615
+ "optimizer_updates": completed_steps,
616
+ "budget": manifest["branches"],
617
+ },
618
+ )
619
+ return result
620
+
621
+
622
+ def audit(out, device="cuda:0"):
623
+ """Reload every saved node from parent plus exact tensors and re-score it."""
624
+ device, out = _configure(device), Path(out)
625
+ manifest = json.loads((out / "run.json").read_text())
626
+ spec = manifest["spec"]
627
+ if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]:
628
+ raise AssertionError("Parent checkpoint hash changed")
629
+ parent, world, parent_spec = _load_parent(spec["parent_dir"], device)
630
+ if model_digest(parent) != manifest["parent_model_sha256"]:
631
+ raise AssertionError("Parent model digest changed")
632
+ cases, qualification = graph_cases(
633
+ parent_spec,
634
+ seed=spec.get("candidate_seed", 780011),
635
+ per_cell=spec.get("per_cell", 2),
636
+ replay_n=spec.get("replay_n", 32),
637
+ )
638
+ if "case_ids" in spec:
639
+ cases = [c for c in cases if c["case_id"] in spec["case_ids"]]
640
+ if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]:
641
+ raise AssertionError("Graph-selected cases changed")
642
+ if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]:
643
+ raise AssertionError("World qualification changed")
644
+ summary = json.loads((out / "complete.json").read_text())
645
+ rates = spec.get("learning_rates", [spec.get("lr", 1e-4)])
646
+ expected_branches = {
647
+ (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham")
648
+ }
649
+ actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]]
650
+ if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches:
651
+ raise AssertionError("The fixed paired branch matrix is incomplete")
652
+ root_learning = json.loads((out / "learning.json").read_text())
653
+ nodes = spec.get("nodes", list(DEFAULT_NODES))
654
+ expected_evaluations = len(actual_branches) * len(nodes)
655
+ if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list(
656
+ range(expected_evaluations)
657
+ ):
658
+ raise AssertionError("Root learning evaluation indices are incomplete or repeated")
659
+ for index, row in enumerate(root_learning):
660
+ branch_index, node_index = divmod(index, len(nodes))
661
+ updates = branch_index * nodes[-1] + nodes[node_index]
662
+ if (
663
+ (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index]
664
+ or row["branch_step"] != nodes[node_index]
665
+ or row["optimizer_updates"] != updates
666
+ or row["target_supervised_tokens"] != updates * 3
667
+ or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3
668
+ or "supervised_tokens" in row
669
+ ):
670
+ raise AssertionError("Root learning optimizer or exposure accounting changed")
671
+ batch_size = spec.get("eval_batch_size", 512)
672
+ checked_nodes, checked_predictions, max_error = 0, 0, 0.0
673
+ for case in cases:
674
+ tasks, originals = case_tasks(world, case)
675
+ parent_correct = _parent_masks(parent, originals, device, batch_size)
676
+ for branch in summary["branches"]:
677
+ if branch["case_id"] != case["case_id"]:
678
+ continue
679
+ directory = out / branch["path"]
680
+ branch_spec = json.loads((directory / "run.json").read_text())
681
+ target = tasks["E_new" if branch["arm"] == "edit" else "E_old"]
682
+ target_batch = answer_batch(target, device)
683
+ replay_batch = answer_batch(tasks["R_atomic"], device)
684
+ with torch.no_grad():
685
+ reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1)
686
+ expected_hashes = {
687
+ "old_fact_sha256": _hash_json(case["old_fact"]),
688
+ "new_fact_sha256": _hash_json(case["new_fact"]),
689
+ "target_batch_sha256": _batch_hash(target_batch),
690
+ "replay_batch_sha256": _batch_hash(replay_batch),
691
+ "parent_reference_sha256": _batch_hash((reference,)),
692
+ }
693
+ if any(branch_spec[key] != value for key, value in expected_hashes.items()):
694
+ raise AssertionError("Target or paired replay provenance changed")
695
+ history = json.loads((directory / "learning.json").read_text())
696
+ if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)):
697
+ raise AssertionError("Saved edit node matrix is incomplete")
698
+ if (
699
+ file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt")
700
+ != branch["tensor_file_sha256"]
701
+ ):
702
+ raise AssertionError("Final exact tensor file hash changed")
703
+ for record in history:
704
+ state = torch.load(
705
+ directory / f"tensors-{record['step']:06d}.pt",
706
+ map_location="cpu",
707
+ weights_only=True,
708
+ )
709
+ model = copy.deepcopy(parent).eval()
710
+ selected = editable_parameters(
711
+ model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0)
712
+ )
713
+ if set(state["edited_tensors"]) != set(selected):
714
+ raise AssertionError("Unexpected edited tensor scope")
715
+ merged = model.state_dict()
716
+ merged.update(state["edited_tensors"])
717
+ model.load_state_dict(merged)
718
+ if model_digest(model) != record["model_sha256"]:
719
+ raise AssertionError("Exact saved tensors did not reconstruct the model")
720
+ metrics, predictions = evaluate_case(
721
+ model,
722
+ tasks,
723
+ originals,
724
+ parent_correct,
725
+ case["role"],
726
+ device,
727
+ batch_size,
728
+ )
729
+ with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved:
730
+ if set(saved.files) != set(predictions):
731
+ raise AssertionError("Prediction keys changed")
732
+ for name, actual in predictions.items():
733
+ if name.endswith("answer_nll"):
734
+ np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5)
735
+ if len(actual):
736
+ max_error = max(
737
+ max_error, float(np.max(np.abs(actual - saved[name])))
738
+ )
739
+ else:
740
+ np.testing.assert_array_equal(actual, saved[name])
741
+ checked_predictions += actual.size
742
+ for name, values in metrics.items():
743
+ for key, value in values.items():
744
+ expected = record["metrics"][name][key]
745
+ if key == "answer_nll" and value is not None:
746
+ np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5)
747
+ elif value != expected:
748
+ raise AssertionError(f"Re-scoring mismatch: {name}/{key}")
749
+ checked_nodes += 1
750
+ result = {
751
+ "passed": True,
752
+ "nodes": checked_nodes,
753
+ "array_elements": checked_predictions,
754
+ "max_nll_error": max_error,
755
+ "case_sha256": manifest["case_sha256"],
756
+ "finished_utc": utc(),
757
+ }
758
+ write_json(out / "audit.json", result)
759
+ return result
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_tracking.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Use the existing W&B sidecar, finishing only after the independent audit."""
2
+
3
+ import argparse
4
+ import fcntl
5
+ import importlib
6
+ import json
7
+ import os
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from . import experiment_tracking as tracking
12
+
13
+
14
+ class ContainerSDK:
15
+ def __init__(self, sdk, runtime):
16
+ self.sdk, self.runtime = sdk, runtime
17
+
18
+ def __getattr__(self, name):
19
+ return getattr(self.sdk, name)
20
+
21
+ def Settings(self, **options):
22
+ options.pop("x_stats_pid", None)
23
+ if self.runtime:
24
+ options["x_stats_pid"] = self.runtime["host_pid"]
25
+ options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],)
26
+ return self.sdk.Settings(**options)
27
+
28
+
29
+ class AuditedRunTracker(tracking.ArtifactRunTracker):
30
+ def __init__(self, sdk, batch, path, settings):
31
+ runtime_path = path / "container-runtime.json"
32
+ runtime = tracking.read_json(runtime_path)
33
+ super().__init__(ContainerSDK(sdk, runtime), batch, path, settings)
34
+ self.run.config.update(
35
+ {
36
+ key: self.metadata[key]
37
+ for key in (
38
+ "parent_spec",
39
+ "cases",
40
+ "learning_step_unit",
41
+ "status_step_unit",
42
+ )
43
+ if key in self.metadata
44
+ }
45
+ )
46
+ if runtime:
47
+ self.run.config.update({"container_runtime": runtime})
48
+
49
+ def poll(self):
50
+ history = tracking.read_json(self.path / "learning.json")
51
+ previous = None
52
+ for record in history:
53
+ step = int(record["step"])
54
+ if step > self.cursor:
55
+ metrics = tracking.learning_metrics(record, previous)
56
+ for key in ("case", "case_id", "condition", "variant", "arm"):
57
+ if key in record:
58
+ metrics["condition/" + key] = record[key]
59
+ if "optimizer_updates" in record:
60
+ metrics["evaluation/index"] = step
61
+ metrics["condition/step_unit"] = "evaluation_index"
62
+ metrics.pop("perf/updates_per_second", None)
63
+ metrics.pop("perf/training_ms_per_update", None)
64
+ if previous is not None:
65
+ seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0)
66
+ updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0)
67
+ if seconds > 0:
68
+ metrics["perf/updates_per_second"] = updates / seconds
69
+ self.run.log(metrics, step=step)
70
+ self.cursor = step
71
+ self.state["last_logged_step"] = step
72
+ tracking.write_json(self.state_path, self.state)
73
+ previous = record
74
+ status_path = self.path / "status.json"
75
+ if status_path.exists():
76
+ self.run.summary["training_state"] = tracking.read_json(status_path).get("state")
77
+ failed = (self.path / "failure.json").exists()
78
+ audit_path = self.path / "audit.json"
79
+ audit = tracking.read_json(audit_path) if audit_path.exists() else {}
80
+ audited = audit.get("passed") is True
81
+ complete = (self.path / "complete.json").exists() and audited
82
+ self.run.summary["has_failure_record"] = failed
83
+ self.run.summary["independently_reloaded"] = audited
84
+ if complete or failed:
85
+ self.run.summary["scientific_final_step"] = self.cursor
86
+ self.run.finish(exit_code=1 if failed else 0)
87
+ # Preserve the authoritative resume cursor even when every point
88
+ # was already on the server and this process logged no new points.
89
+ self.state["last_logged_step"] = self.cursor
90
+ tracking.write_json(self.state_path, self.state)
91
+ return True
92
+ return False
93
+
94
+
95
+ def discover_runs(runs_dir):
96
+ return {
97
+ path
98
+ for path in Path(runs_dir).glob("*")
99
+ if (path / "run.json").exists() and (path / "learning.json").exists()
100
+ }
101
+
102
+
103
+ def final_step(path):
104
+ history = tracking.read_json(path / "learning.json")
105
+ return max((int(record["step"]) for record in history), default=-1)
106
+
107
+
108
+ def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None):
109
+ """Drain late-created runs and late final nodes before terminal exit.
110
+
111
+ SDK initialization and uploads may take longer than an entire scientific
112
+ run. Consequently, a scan made before those calls is never an exit proof.
113
+ Finished runs stay in this process's cursor map and are reopened only if
114
+ their saved learning trajectory acquired an unlogged final node.
115
+ """
116
+ root, runs_dir = Path(root), Path(runs_dir)
117
+ tracker_factory = tracker_factory or AuditedRunTracker
118
+ active, finished = {}, {}
119
+ try:
120
+ while True:
121
+ for path in sorted(discover_runs(runs_dir)):
122
+ if path in active or path in finished:
123
+ continue
124
+ active[path] = tracker_factory(sdk, root, path, settings)
125
+ print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True)
126
+ for path, tracker in list(active.items()):
127
+ current = tracking.read_json(path / "run.json")
128
+ if current.get("pid") != tracker.metadata.get("pid"):
129
+ tracker.close()
130
+ tracker = tracker_factory(sdk, root, path, settings)
131
+ active[path] = tracker
132
+ if tracker.poll():
133
+ finished[path] = tracker.cursor
134
+ del active[path]
135
+ if once:
136
+ return {str(path): cursor for path, cursor in finished.items()}
137
+ manifest = root / "controller-state.json"
138
+ state = tracking.read_json(manifest) if manifest.exists() else {}
139
+ terminal = state.get("state") in {
140
+ "complete",
141
+ "finished_with_failures",
142
+ "development_prerequisite_not_met",
143
+ }
144
+ # Rescan AFTER all SDK calls and after reading the controller's
145
+ # terminal state, so runs born during initialization cannot vanish.
146
+ fresh = discover_runs(runs_dir)
147
+ stale = {path for path, cursor in finished.items() if final_step(path) > cursor}
148
+ for path in stale:
149
+ del finished[path]
150
+ if terminal and not active:
151
+ expected = {runs_dir / name for name in state.get("completed", [])}
152
+ if missing := expected - fresh:
153
+ raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}")
154
+ if fresh <= finished.keys():
155
+ result = {
156
+ "passed": True,
157
+ "registered_runs": len(finished),
158
+ "runs": {
159
+ path.name: {
160
+ "last_logged_step": finished[path],
161
+ "final_step": final_step(path),
162
+ }
163
+ for path in sorted(fresh)
164
+ },
165
+ }
166
+ tracking.write_json(root / "tracking-completion.json", result)
167
+ return result
168
+ if fresh - (active.keys() | finished.keys()):
169
+ continue
170
+ time.sleep(settings["poll_seconds"])
171
+ finally:
172
+ for tracker in active.values():
173
+ tracker.close()
174
+
175
+
176
+ def main():
177
+ parser = argparse.ArgumentParser(description=__doc__)
178
+ parser.add_argument("--root", type=Path, required=True)
179
+ parser.add_argument("--runs-dir", type=Path)
180
+ parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS)
181
+ parser.add_argument("--entity")
182
+ parser.add_argument("--project")
183
+ parser.add_argument("--mode", choices=("online", "offline"))
184
+ parser.add_argument("--once", action="store_true")
185
+ args = parser.parse_args()
186
+ settings = tracking.read_json(args.defaults)
187
+ for key in ("entity", "project", "mode"):
188
+ settings[key] = (
189
+ getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key]
190
+ )
191
+ if not settings["enabled"]:
192
+ raise SystemExit("Experiment tracking is disabled in the selected defaults")
193
+ local = args.root / "tracking-wandb"
194
+ local.mkdir(parents=True, exist_ok=True)
195
+ sdk = importlib.import_module("wandb")
196
+ with (local / "tracker.lock").open("w") as lock:
197
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
198
+ tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__})
199
+ drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once)
200
+
201
+
202
+ if __name__ == "__main__":
203
+ main()