Archive experiment updates 2026-10-08 (27/119)
Browse filesFile-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)
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_transfer.pyAdded+653
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_readout_control.pyAdded+373
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_relation_response.pyAdded+187
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.pyAdded+372
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.pyAdded+192
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_control.pyAdded+242
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.pyAdded+446
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.pyAdded+446
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.pyAdded+327
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_train.pyAdded+353
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_reencoding.pyAdded+438
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_workspace.pyAdded+1112
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_controls.pyAdded+64
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_scaling.pyAdded+193
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/cli.pyAdded+32
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/composition_curves.pyAdded+477
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/curve_tracking.pyAdded+36
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step.pyAdded+669
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.pyAdded+371
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_mechanism.pyAdded+589
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiment_tracking.pyAdded+298
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiments.pyAdded+39
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth.pyAdded+431
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_bridge.pyAdded+631
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_data.pyAdded+281
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_extension.pyAdded+73
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_data.pyAdded+346
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.pyAdded+549
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_model.pyAdded+108
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_train.pyAdded+214
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop.pyAdded+278
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_data.pyAdded+397
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_train.pyAdded+261
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_data.pyAdded+396
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_followup.pyAdded+103
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_future.pyAdded+148
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_interface.pyAdded+566
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_learning.pyAdded+187
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_model.pyAdded+339
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_train.pyAdded+811
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/independent_alignment.pyAdded+124
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_editing.pyAdded+759
- docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_tracking.pyAdded+203
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653"""Prospective v2.13: forward-preserving path interventions and local transfer.
Only a single MLP output weight is differentiated/updated in production.Downstream parameters are frozen; the custom attention paths alter its input VJP."""
import argparseimport fcntlimport hashlibimport itertoolsimport jsonimport osimport platformimport subprocessimport sysimport timefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import MethodType
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_cross import edit_pair, make_cross_worldfrom .bios_cross_train import tensor_queriesfrom .bios_data import EOS, array_hash, write_jsonfrom .bios_model import CausalLM, ModelConfig
ROOT = Path(__file__).resolve().parents[2]CONFIG = ROOT / "configs/bios-path-transfer-v1.json"ARMS = ("full", "no_cross", "no_mlp", "fixed_qk")
def stamp(): return datetime.now(timezone.utc).isoformat()
def sha(path): result = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): result.update(chunk) return result.hexdigest()
def tensor_sha(value): return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
def inner(a, b): return (a.double() * b.double()).sum().item()
def norm(a): return a.double().norm().item()
def relative(a, b): return norm(a - b) / max(norm(b), 1e-30)
def cosine(a, b): return inner(a, b) / max(norm(a) * norm(b), 1e-30)
def attention_surrogate(module, x, mode): """Correct input Jacobian for frozen QK, or only the diagonal position blocks.
no_cross makes T copies of the input: copy s only differentiates x_s, then computes output s with the full original causal context. Thus Q_s, K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. """ batch, length, width = x.shape heads, dim = module.heads, width // module.heads if mode == "no_cross": expanded = x[:, None].expand(batch, length, length, width) diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] routed = expanded.detach() + diagonal * (expanded - expanded.detach()) q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) index = torch.arange(length, device=x.device) q = q[:, index, index] # B, query, H, D scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() a = scores.masked_fill(~mask, -torch.inf).softmax(-1) output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) else: q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() a = scores.masked_fill(~mask, -torch.inf).softmax(-1) if mode == "fixed_qk": a = a.detach() elif mode != "manual_full": raise ValueError(mode) output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) return module.proj(output)
@contextmanagerdef path_mode(model, layer, arm): if arm not in (*ARMS, "manual_full"): raise ValueError(arm) saved = [] try: for block in model.blocks[layer + 1 :]: if arm == "no_mlp": module = block.mlp original = module.forward
def stopped(self, x, original=original): with torch.no_grad(): return original(x)
module.forward = MethodType(stopped, module) saved.append((module, original)) elif arm != "full": module = block.attention original = module.forward
def altered(self, x, original=original, arm=arm): with torch.no_grad(): reference = original(x) surrogate = attention_surrogate(self, x, arm) return reference + (surrogate - surrogate.detach())
module.forward = MethodType(altered, module) saved.append((module, original)) yield finally: for module, original in saved: module.forward = original
def cases(world): result = [] for chain in range(2): pair = edit_pair(world, chain) for group in pair["groups"]: members = np.flatnonzero(world.memberships[chain] == group) eligible = members[ np.isin(world.derived_ids[chain, members], world.heldout_ids) & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) ] if not len(eligible): raise ValueError("No prespecified heldout conflict person") person = int(eligible[0]) others = members[ (members != person) & ~world.exceptions[chain, members] & np.isin(world.derived_ids[chain, members], world.heldout_ids) ] if not len(others): raise ValueError("No prespecified second heldout person") other = int(others[0]) distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) root = int(world.root_ids[chain, group]) actual = int(world.actual_ids[chain, person]) default = int(pair["coherent"][root]) alternative = int(pair["exception"][actual]) if default == alternative: raise ValueError("Selected person is not a new conflict") for kind in ("root", "coherent", "conflict"): source = root if kind == "root" else actual target = alternative if kind == "conflict" else default associated = actual if kind == "root" else root ids = [ source, int(world.derived_ids[chain, person]), int(world.derived_ids[chain, other]), associated, int(world.actual_ids[1 - chain, person]), int(world.actual_ids[chain, distant]), ] targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] result.append( { "name": f"chain-{chain}-group-{int(group)}-{kind}", "chain": chain, "group": int(group), "kind": kind, "person": person, "other_person": other, "ids": ids, "targets": targets, "old_targets": world.answers[ids].tolist(), "roles": [ "source", "derived_same", "derived_other", "associated", "retention_local", "retention_distant", ], } ) return result
def example_data(world, case, device): # Use the original interface, including teacher-forced answer for EOS loss. targets = world.answers.copy() targets[case["ids"]] = case["targets"] all_data = tensor_queries(world, device, targets) ids = torch.tensor(case["ids"], device=device) return {key: value[ids] for key, value in all_data.items()}
def subset(data, ids): return {key: value[ids] for key, value in data.items()}
def losses(logits, labels): return ( F.cross_entropy( logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" ) .reshape(-1, 2) .mean(-1) )
def measure(model, data, layer, arm): projection = model.blocks[layer].mlp.down captured = {}
def hook(module, inputs, output): captured["z"], captured["h"] = inputs[0], output
handle = projection.register_forward_hook(hook) try: with path_mode(model, layer, arm): logits = model(data["tokens"], data["positions"]) loss = losses(logits, data["labels"]) actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) z = captured["z"].detach() delta = delta.detach() per_position = torch.einsum("btd,btk->btdk", delta, z) mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) mask.scatter_(1, data["positions"], True) g = per_position.sum(1) supervised = (per_position * mask[:, :, None, None]).sum(1) unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) return { "z": z, "delta": delta, "g": g, "supervised": supervised, "unsupervised": unsupervised, "mask": mask, "loss": loss.detach(), "logits": logits.detach(), "reconstruction_error": relative(g.sum(0), actual), "decomposition_error": relative(supervised + unsupervised, g), } finally: handle.remove()
@torch.no_grad()def assess(model, data): logits = model(data["tokens"], data["positions"]) loss = losses(logits, data["labels"]) first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) continuation = data["tokens"].clone() rows = torch.arange(len(first), device=first.device) continuation[rows, data["lengths"]] = first ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) return loss, first, ended
def frozen_files(config): paths = [ CONFIG, Path(__file__), ROOT / "scripts/run_bios_path_transfer.py", ROOT / "tests/test_bios_path_transfer.py", ] for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): paths.append(ROOT / "src/llm_memory_editability" / name) for world in config["worlds"]: directory = ROOT / config["source_world_root"] / f"world-{world}" paths += [ directory / "world.npz", directory / "metadata.json", directory / "evaluation.npz", ] for world, seed in itertools.product(config["worlds"], config["seeds"]): directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" paths += [directory / "config.json", directory / "learning-complete.json"] paths += [directory / f"model-{step}.pt" for step in config["states"]] return paths
def freeze(config): directory = ROOT / config["artifacts"] directory.mkdir(parents=True, exist_ok=True) lock_path = directory / "preregistration-lock.json" if lock_path.exists(): raise FileExistsError("Cannot replace a prospective lock") protocol = ( "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] ) (directory / "preregistration.md").write_text(protocol) manifests = {} for world in config["worlds"]: generated = make_cross_world(world, ROOT / config["source_world_root"]) selected = cases(generated) if len(selected) != config["cases_per_state"]: raise ValueError("Case count mismatch") manifests[str(world)] = { "truth_sha256": array_hash(generated.answers), "prompts_sha256": array_hash(generated.prompts), "cases": selected, } write_json(directory / "cases.json", manifests) sources = {} for path in frozen_files(config): relative_path = path.relative_to(ROOT) sources[str(relative_path)] = sha(path) if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): destination = directory / "frozen-files" / relative_path destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(path.read_bytes()) lock = { "created_at": stamp(), "config": config, "sources": sources, "protocol_sha256": sha(directory / "preregistration.md"), "cases_sha256": sha(directory / "cases.json"), "torch": torch.__version__, "numpy": np.__version__, "python": platform.python_version(), } write_json(lock_path, lock) return {"path": str(lock_path), "sha256": sha(lock_path)}
def verify_lock(config): directory = ROOT / config["artifacts"] path = directory / "preregistration-lock.json" lock = json.loads(path.read_text()) if lock["config"] != config or lock["torch"] != torch.__version__: raise ValueError("Frozen config/runtime mismatch") for name, digest in lock["sources"].items(): if sha(ROOT / name) != digest: raise ValueError("Frozen input changed: " + name) for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): if sha(directory / name) != lock[key]: raise ValueError("Prospective manifest changed") return sha(path)
def save_factors(path, baseline, sources, data): arrays = { "positions": data["positions"].cpu().numpy(), "labels": data["labels"].cpu().numpy(), "tokens": data["tokens"].cpu().numpy(), } for prefix, result in [("evaluation", baseline), *sources.items()]: for key in ("z", "delta", "loss"): arrays[prefix + "_" + key] = result[key].cpu().numpy() np.savez_compressed(path, **arrays)
def run_case(model, world, case, config, destination): layer = config["target_layer"] w = model.blocks[layer].mlp.down.weight parent = w.detach().clone() frozen_before = { name: tensor_sha(value) for name, value in model.state_dict().items() if name != config["target_parameter"] } data = example_data(world, case, w.device) baseline = measure(model, data, layer, "full") before, old_prediction, old_ended = assess(model, data) sources, diagnostics, updates = {}, [], [] with torch.no_grad(): if not torch.equal(before, baseline["loss"]): raise ValueError("Evaluation/gradient forward mismatch") for arm in config["arms"]: source = measure(model, subset(data, slice(0, 1)), layer, arm) sources[arm] = source error = (source["logits"] - sources["full"]["logits"]).abs().max().item() if error > config["forward_tolerance"]: raise ValueError(f"Forward preservation failed: {error}") if ( max(source["reconstruction_error"], baseline["reconstruction_error"]) > config["gradient_tolerance"] ): raise ValueError("Outer-product reconstruction failed") direction = source["g"][0] gfull = sources["full"]["g"][0] if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") for j, role in enumerate(case["roles"]): row = { "arm": arm, "role": role, "probe": j, "forward_error": error, "reconstruction_error": source["reconstruction_error"], "gradient_norm": norm(direction), "gradient_cosine_full": cosine(direction, gfull), "supervised_norm": norm(source["supervised"]), "unsupervised_norm": norm(source["unsupervised"]), "kernel": inner(baseline["g"][j], direction), "source_loss": source["loss"].item(), "probe_loss": before[j].item(), } for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) diagnostics.append(row) for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): denominator = norm(gfull if scale == "shared_lr" else direction) eta = fraction * norm(parent) / denominator if denominator else 0.0 with torch.no_grad(): w.copy_(parent - eta * direction) displacement = w.detach() - parent weight_hash = tensor_sha(w) after, predicted_token, ended = assess(model, data) predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) for j, role in enumerate(case["roles"]): updates.append( { "arm": arm, "scale": scale, "fraction": fraction, "eta": eta, "update_norm": norm(displacement), "weight_sha256": weight_hash, "role": role, "probe": j, "id": case["ids"][j], "target": case["targets"][j], "old_target": case["old_targets"][j], "before": before[j].item(), "after": after[j].item(), "observed_change": (after[j] - before[j]).item(), "predicted_change": predicted[j].item(), "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), "baseline_prediction": int(old_prediction[j]), "baseline_ended": bool(old_ended[j]), "prediction": int(predicted_token[j]), "ended": bool(ended[j]), } ) with torch.no_grad(): w.copy_(parent) if not torch.equal(w, parent): raise ValueError("Parent weight was not restored") frozen_after = { name: tensor_sha(value) for name, value in model.state_dict().items() if name != config["target_parameter"] } if frozen_before != frozen_after: raise ValueError("A frozen parameter changed") destination.mkdir(parents=True, exist_ok=True) save_factors(destination / "factors.npz", baseline, sources, data) write_json( destination / "measurements.json", {"case": case, "diagnostics": diagnostics, "updates": updates}, ) write_json( destination / "receipt.json", { "finished_at": stamp(), "files": { name: sha(destination / name) for name in ("factors.npz", "measurements.json") }, "baseline_reconstruction_error": baseline["reconstruction_error"], "frozen_parameters_unchanged": True, "parent_restored": True, }, )
def verify_receipt(directory): receipt = json.loads((directory / "receipt.json").read_text()) for name, digest in receipt["files"].items(): if sha(directory / name) != digest: raise ValueError("Receipt mismatch: " + str(directory / name))
def run(config, world_id, seed, device): lock_hash = verify_lock(config) if world_id not in config["worlds"] or seed not in config["seeds"]: raise ValueError("Worker outside the frozen matrix") torch.set_num_threads(2) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False world = make_cross_world(world_id, ROOT / config["source_world_root"]) name = f"world-{world_id}-seed-{seed}-neither" source = ROOT / config["parent_root"] / name out = ROOT / config["output"] / name out.mkdir(parents=True, exist_ok=True) with (out / ".lock").open("a") as stream: fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) started = time.monotonic() write_json( out / "runtime.json", { "started_at": stamp(), "lock_sha256": lock_hash, "device": str(device), "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), "torch": torch.__version__, }, ) for step in config["states"]: checkpoint = torch.load( source / f"model-{step}.pt", map_location="cpu", weights_only=False ) if checkpoint["step"] != step: raise ValueError("Parent step mismatch") model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) model.load_state_dict(checkpoint["model"]) model.eval() for pname, parameter in model.named_parameters(): parameter.requires_grad_(pname == config["target_parameter"]) selected = cases(world) state_out = out / f"step-{step}" state_out.mkdir(exist_ok=True) # Original-forward repeated gradient, not a new scientific sample. sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) first = measure(model, sham_data, config["target_layer"], "full") second = measure(model, sham_data, config["target_layer"], "full") sham_error = relative(first["g"], second["g"]) if sham_error > config["gradient_tolerance"]: raise ValueError("Sham gradient failed") write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) for case in selected: destination = state_out / case["name"] if (destination / "receipt.json").exists(): verify_receipt(destination) else: run_case(model, world, case, config, destination) print( json.dumps( { "event": "case", "world": world_id, "seed": seed, "step": step, "case": case["name"], } ), flush=True, ) del model, checkpoint files = { str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file() and path.name not in (".lock", "complete.json") } write_json( out / "complete.json", { "finished_at": stamp(), "seconds": time.monotonic() - started, "lock_sha256": lock_hash, "cases": len(config["states"]) * len(selected), "files": files, }, )
def dispatch(config, gpus): verify_lock(config) output = ROOT / config["output"] output.mkdir(parents=True, exist_ok=True) jobs = list(itertools.product(config["worlds"], config["seeds"])) active, finished = [], [] with (output / ".dispatch.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) while jobs or active: for gpu in gpus: if jobs and not any(item["gpu"] == gpu for item in active): world, seed = jobs.pop(0) path = output / f"world-{world}-seed-{seed}-neither" if (path / "complete.json").exists(): finished.append({"world": world, "seed": seed, "reused": True}) continue log = (output / f"world-{world}-seed-{seed}.log").open("a") env = { **os.environ, "CUDA_VISIBLE_DEVICES": str(gpu), "PYTHONPATH": str(ROOT / "src"), "OMP_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", } command = [ sys.executable, str(ROOT / "scripts/run_bios_path_transfer.py"), "worker", "--world", str(world), "--seed", str(seed), "--device", "cuda:0", ] proc = subprocess.Popen( command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT ) active.append( {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} ) for item in active[:]: code = item["process"].poll() if code is not None: item["log"].close() record = {k: item[k] for k in ("gpu", "world", "seed")} finished.append({**record, "returncode": code}) active.remove(item) write_json( output / "dispatch.json", { "updated_at": stamp(), "pending": jobs, "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], "finished": finished, }, ) if active: time.sleep(2) if any(item.get("returncode", 0) for item in finished): raise RuntimeError("One or more workers failed; inspect preserved logs")
def main(): parser = argparse.ArgumentParser() parser.add_argument("command", choices=("freeze", "worker", "dispatch")) parser.add_argument("--world", type=int) parser.add_argument("--seed", type=int) parser.add_argument("--device", default="cuda:0") parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) args = parser.parse_args() config = json.loads(CONFIG.read_text()) if args.command == "freeze": print(json.dumps(freeze(config))) elif args.command == "worker": run(config, args.world, args.seed, torch.device(args.device)) else: dispatch(config, args.gpus)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373"""H5: original E93 exception edits of all weights except tied token/readout weights."""
import argparseimport fcntlimport jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_worldfrom .bios_cross_continue import ( capture_state, edit_metrics, edit_update, file_hash, restore_state, validate_optimizer,)from .bios_cross_train import evaluate, source_hashes, tensor_queriesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfigfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .bios_train import precision
CHECKPOINTS = (0, 32, 128, 512)SCOPE = "all-freeze-embedding"STUDY = { "protocol": "v2.8-h5-readout-control-E93", "widths": [256, 768], "parent_step": 15360, "worlds": [0, 1], "seeds": [0, 1], "conditions": list(CONDITIONS), "chains": list(CHAINS), "kind": "exception", "scope": SCOPE, "frozen": "token.weight, shared by input embedding and output F.linear readout", "trainable": "all other parameters, including absolute position embedding", "lr": 3e-5, "weight_decay": 0.1, "edit_batch": 128, "replay_batch": 128, "retention_kl": 1.0, "clip_norm": 1.0, "steps": 512, "checkpoints": list(CHECKPOINTS), "resume_every": 32, "models": 24, "edit_cases": 48, "E": 93, "D": 96, "R": 4096, "reference_scopes": ["mlp", "all"], "selection": "all fixed512 endpoints; no best step",}
def validate_study(study): if study != STUDY: raise ValueError("H5 configuration differs from the fixed contract")
def control_sources(): return { **source_hashes(), "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), Path(__file__).name: file_hash(__file__), }
def select_control_parameters(model): """The ordinary model passes this same Parameter directly to F.linear.""" excluded = id(model.token.weight) selected = [] for parameter in model.parameters(): parameter.requires_grad_(id(parameter) != excluded) parameter.grad = None if parameter.requires_grad: selected.append(parameter) assert model.position.weight.requires_grad and not model.token.weight.requires_grad return selected
def sampling_stream(world_seed, chain, steps=512, batch=128): rng = rng_for(world_seed, 908, chain) return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch))
def score_arrays(arrays, truth): for key in ("prediction", "ended", "correct"): if arrays[key].shape != truth.shape: raise ValueError("H5 prediction array shape mismatch") if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: raise ValueError("H5 EOS/correct flags must be Boolean") np.testing.assert_array_equal( arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] ) return arrays
def validate_parent_config(config, world): width = config["model"]["width"] if width not in STUDY["widths"] or config["world"] not in (0, 1): raise ValueError("H5 parent outside original size/world matrix") expected = dict( vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 ) if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": raise ValueError("H5 needs original unrestricted low-prevalence architecture") expected_study = dict( steps=15360, lr=1e-4, documents_per_step=16, facts_per_document=10, QA_per_chain_per_step=20, document_QA_weights=[0.8, 0.2], ) if any(config["study"][key] != value for key, value in expected_study.items()): raise ValueError("H5 parent is not the original learning budget") if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: raise ValueError("H5 parent outside original initialization/organization matrix") if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): raise ValueError("H5 parent source or truth mismatch") if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: raise ValueError("H5 numerical software differs from parent")
def reference_contract(parent, world, old_arrays): hashes = {} for chain, name in enumerate(CHAINS): pair = edit_pair(world, chain) assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 e, r = sampling_stream(world.seed, chain) for scope in ("mlp", "all"): dest = parent / "edits" / f"{name}-exception-{scope}" with np.load(dest / "sets.npz") as actual: for key, value in pair.items(): np.testing.assert_array_equal(actual[key], value) np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) np.testing.assert_array_equal(actual["edit_sampling"], e) np.testing.assert_array_equal(actual["replay_sampling"], r) points = json.loads((dest / "trajectory.json").read_text()) if [point["step"] for point in points] != list(CHECKPOINTS): raise ValueError("Original MLP/All reference checkpoint grid differs") if json.loads((dest / "complete.json").read_text())["status"] != "complete": raise ValueError("Original MLP/All reference incomplete") for step in CHECKPOINTS: with np.load(dest / f"predictions-{step}.npz") as saved: arrays = score_arrays(dict(saved), pair["exception"]) if step == 0: for key in ("prediction", "ended"): np.testing.assert_array_equal(arrays[key], old_arrays[key]) for filename in ( "sets.npz", "trajectory.json", "complete.json", *(f"predictions-{step}.npz" for step in CHECKPOINTS), ): hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) return hashes
def load_parent(parent): config = json.loads((parent / "config.json").read_text()) world = make_cross_world(config["world"]) validate_parent_config(config, world) with np.load(parent / "predictions-15360.npz") as saved: arrays = score_arrays(dict(saved), world.answers) references = reference_contract(parent, world, arrays) checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) complete = json.loads((parent / "learning-complete.json").read_text()) if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: raise ValueError("H5 parent checkpoint identity differs") if ( complete["status"] != "complete" or state_hash(checkpoint["model"]) != complete["model_sha256"] ): raise ValueError("H5 parent learning checkpoint is not verified complete") provenance = dict( directory=str(parent), model_sha256=complete["model_sha256"], reference_files_sha256=references, files_sha256={ name: file_hash(parent / name) for name in ( "config.json", "model-15360.pt", "predictions-15360.npz", "learning-complete.json", ) }, ) return config, world, arrays, checkpoint, provenance
def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" if (dest / "complete.json").exists(): return dest.mkdir(parents=True, exist_ok=True) model.load_state_dict(baseline) selected = select_control_parameters(model) frozen = baseline["token.weight"] pair = edit_pair(world, chain) e, r = sampling_stream(world.seed, chain) atomic_numpy_save( dest / "sets.npz", **pair, old_correct=parent_arrays["correct"], edit_sampling=e, replay_sampling=r, ) new_data = tensor_queries(world, device, pair["exception"]) model.eval() references = [] with torch.no_grad(), precision(device): for begin in range(0, len(pair["replay"]), 256): ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) references = torch.cat(references) optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") first, timeline, seconds = 0, [], 0.0 if (dest / "resume.pt").exists(): saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: raise ValueError("H5 resume identity differs") if not 0 <= saved["step"] <= 512 or saved["step"] % 32: raise ValueError("H5 resume step differs") if saved["step"]: validate_optimizer(saved["optimizer"], saved["step"], 3e-5) restore_state(model, optimizer, saved, device) first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] for step in range(first, 513): if step in CHECKPOINTS: if not torch.equal(model.token.weight.detach().cpu(), frozen): raise ValueError("Frozen input/output token weights changed") if not timeline or timeline[-1]["step"] != step: arrays = score_arrays( evaluate(model, new_data, pair["exception"]), pair["exception"] ) if step == 0: for key in ("prediction", "ended"): np.testing.assert_array_equal(arrays[key], parent_arrays[key]) timeline.append( dict( step=step, edit_seconds=seconds, **edit_metrics(world, pair, arrays, parent_arrays["correct"]), ) ) atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) write_json(dest / "trajectory.json", timeline) if step % 32 == 0: atomic_torch_save( capture_state( model, optimizer, device, step=step, timeline=timeline, seconds=seconds, identity_sha256=identity_hash, case=dest.name, ), dest / "resume.pt", ) if step == 512: break ei = torch.as_tensor(pair["E"][e[step]], device=device) ri = torch.as_tensor(pair["replay"][r[step]], device=device) choices = torch.as_tensor(r[step], device=device) if device.type == "cuda": torch.cuda.synchronize(device) start = time.perf_counter() edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) if device.type == "cuda": torch.cuda.synchronize(device) seconds += time.perf_counter() - start atomic_torch_save( dict(model=model.state_dict(), config=model.config_dict(), step=512), dest / "model-final.pt", ) write_json( dest / "complete.json", dict( status="complete", scope=SCOPE, kind="exception", chain=CHAINS[chain], final=timeline[-1], model_sha256=state_hash(model.state_dict()), frozen_token_sha256=state_hash({"token.weight": frozen}), ), ) print( json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True )
def run(args): validate_study(json.loads(Path(args.config).read_text())) parent, output = Path(args.parent).resolve(), Path(args.output).resolve() if parent == output or parent in output.parents or output in parent.parents: raise ValueError("H5 output must be separate from immutable parent") output.mkdir(parents=True, exist_ok=True) with (output / ".lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) torch.set_num_threads(args.threads) config, world, arrays, checkpoint, provenance = load_parent(parent) device = torch.device(args.device) identity = dict( world=world.seed, seed=config["seed"], condition=config["condition"], width=config["model"]["width"], study=STUDY, sources=control_sources(), parent=provenance, torch=torch.__version__, cuda=torch.version.cuda, numpy=np.__version__, device_type=device.type, ) path = output / "config.json" if path.exists() and json.loads(path.read_text()) != identity: raise ValueError("Frozen H5 worker contract changed") if not path.exists(): write_json(path, identity) if (output / "complete.json").exists(): return if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True torch.manual_seed(config["seed"]) if device.type == "cuda": torch.cuda.manual_seed_all(config["seed"]) model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) model.load_state_dict(checkpoint["model"]) baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} data = tensor_queries(world, device) try: observed = score_arrays(evaluate(model, data, world.answers), world.answers) for key in ("prediction", "ended", "correct"): np.testing.assert_array_equal(observed[key], arrays[key]) for chain in range(2): run_case( model, baseline, data, world, arrays, chain, output, file_hash(path), device ) write_json( output / "complete.json", dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), ) except Exception as error: write_json( output / "failure.json", dict(type=type(error).__name__, message=str(error), time=time.time()), ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--parent", required=True) parser.add_argument("--output", required=True) parser.add_argument("--config", default="configs/bios-readout-control-v1.json") parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""A paired four-cell test of which fact controls a composite answer.
The editor is unchanged. Derivative probes use answer contrasts, never acomposite target loss. Isolated directions preserve the OTHER direct query'stwo a/c and b/c contrasts to first order, not its entire output distribution."""
from dataclasses import replace
import torch
from .bios_direction import Suffixfrom .bios_direction_cross import cross_tasks
CELLS = ("aa", "ab", "ba", "bb")LAYER = 4
def factorial_tasks(world, seed, device): """Rows select root targets; columns select personal targets; a/b stay fixed.""" originals = cross_tasks(world, seed, device) result = [] for pair_index in range(6): base = originals[2 * pair_index] for cell in CELLS: labels, tokens = base.labels.clone(), base.tokens.clone() root, actual = base.sets["E"] labels[root, 0] = base.metadata[cell[0]] labels[actual, 0] = base.metadata[cell[1]] labels[base.sets["D"], 0] = base.metadata[cell[0]] rows = torch.arange(len(tokens), device=tokens.device) tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] metadata = dict( base.metadata, cell=cell, pair_index=pair_index, kind="coherent" if cell[0] == cell[1] else "independent", root_target=base.metadata[cell[0]], actual_target=base.metadata[cell[1]], ) result.append( replace( base, name=base.name.rsplit("-", 1)[0] + "-" + cell, labels=labels, tokens=tokens, metadata=metadata, ) ) return result
def check_reused_task(task, manifest): """Compare actual information, including teacher-forced EOS prefixes.""" current = task.manifest() for key in ("sets", "labels", "old_labels", "tokens_sha256"): assert current[key] == manifest[key], key for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): assert current["metadata"][key] == manifest["metadata"][key], key
def make_probe(model, task): ids = task.sets["E"] + task.sets["D_focal"] positions = task.positions[ids, :1] tokens = task.tokens[ids, :5].clone() # No desired answer is present even at masked future positions. tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) return Suffix(model, LAYER, tokens, positions)
def values(probe, weight, metadata): logits = probe(weight[None])[0, :, 0] a, b, c = (metadata[k] for k in ("a", "b", "c")) contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) return logits, contrasts
def derivatives(probe, weight, metadata): w = weight.detach().clone().requires_grad_() logits, contrasts = values(probe, w, metadata) gradients = torch.stack( [ torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] for i in range(3) for j in range(2) ] ).reshape(3, 2, *w.shape) return logits.detach(), contrasts.detach(), gradients.detach()
def isolated_directions(gradients): """Minimum-norm direct-fact controls; D is excluded from construction.
A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), hence its a-b contrast by 1; the other fact has both contrasts fixed. """ g = gradients[:2].flatten(0, 1).flatten(1).double() gram = g @ g.T eig, vec = torch.linalg.eigh(gram) keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) controls = targets.double() @ inverse @ g achieved = controls @ g.T gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() coefficients = controls @ gd residual = gd - (gd @ g.T) @ inverse @ g summary = { "rank": int(keep.sum()), "spectrum": eig.cpu().tolist(), "control_residual": float((achieved - targets).abs().max()), "root_response": float(coefficients[0]), "actual_response": float(coefficients[1]), "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), "root_control_norm": float(controls[0].norm()), "actual_control_norm": float(controls[1].norm()), } return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary
@torch.no_grad()def calibrate_controls(probe, weight, metadata, gradients, magnitudes): controls, summary = isolated_directions(gradients) baseline_logits, baseline = values(probe, weight, metadata) rows = [] if summary["control_residual"] > 1e-5: return summary, rows for index, name in enumerate(("root", "actual")): for magnitude in magnitudes: for sign in (-1, 1): delta = sign * magnitude * controls[index] cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) delta = delta * cap changed, after = values(probe, weight + delta, metadata) observed = after - baseline predicted = (gradients.double() * delta.double()).sum((-1, -2)) other = 1 - index logp = baseline_logits.double().log_softmax(-1) new_logp = changed.double().log_softmax(-1) kl = (logp.exp() * (logp - new_logp)).sum(-1) rows.append( dict( control=name, magnitude=magnitude, sign=sign, cap=cap, actual_target_increment=sign * magnitude * cap, delta_norm=float(delta.norm()), predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), other_ac_bc_drift=float(observed[other].abs().max()), other_output_kl=float(kl[other]), direct_argmax_changes=int( (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() ), ) ) return summary, rows
def first_adam_update(model, task, config): """Exact first-step algebra of the frozen soft-functional Adam editor.""" ids = task.sets["E"] + task.sets["R"] suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() logits = suffix(w[None])[0] logp = logits.double().log_softmax(-1) labels = task.labels[ids] ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) n = len(task.sets["E"]) # The original-parent KL has exactly zero derivative at the parent. loss = ce[:n].mean() + ce[n:].mean() gradient = torch.autograd.grad(loss, w)[0] m, v = 0.1 * gradient, 0.001 * gradient.square() t = torch.ones((), device=w.device) raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) return config["lr"] * raw
def factorial_effects(margins): aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) return dict( intercept=(aa + ab + ba + bb) / 4, root=(aa + ab - ba - bb) / 4, actual=(aa - ab + ba - bb) / 4, interaction=(aa - ab - ba + bb) / 4, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372"""Locked independent-world behavioral confirmation, never a route-mediation claim.
The original learning implementation and the audited E39 update implementationare called directly. An external prospective lock is mandatory before execution."""
import argparseimport fcntlimport hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_cross import CHAINS, CONDITIONS, make_cross_worldfrom .bios_cross_train import learning, source_hashesfrom .bios_data import write_jsonfrom .bios_organization_train import atomic_numpy_save, state_hashfrom .bios_path_diagnostics import autonomous_two_stepfrom .bios_shortcut_confirmation_sets import make_confirmation_edit_pairfrom .bios_shortcut_control import high_exception_worldfrom .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDYfrom .bios_shortcut_edit_v2 import run_casefrom .bios_shortcut_matched_edit import KINDS, PHASES
PROTOCOL = "v2.9-shortcut-behavior-confirmation"WORLDS = tuple(range(100, 108))LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360)
def file_hash(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: while chunk := stream.read(4 * 1024 * 1024): digest.update(chunk) return digest.hexdigest()
def confirmation_sources(): directory = Path(__file__).parent return { **source_hashes(), "scripts/prepare_bios_shortcut_confirmation.py": file_hash( directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" ), **{ name: file_hash(directory / name) for name in ( "bios_shortcut_confirmation.py", "bios_shortcut_confirmation_sets.py", "bios_shortcut_control.py", "bios_shortcut_matched_edit.py", "bios_shortcut_edit_v2.py", "bios_cross_continue.py", "bios_path_diagnostics.py", ) }, }
def validate_config(config): expected = { "protocol": PROTOCOL, "worlds": list(WORLDS), "seeds": [0, 1], "conditions": list(CONDITIONS), "phases": list(PHASES), "chains": list(CHAINS), "supports": [0, 1], "width": 256, "layers": 8, "heads": 4, "steps": 15360, "checkpoints": list(LEARNING_CHECKPOINTS), "lr": 0.0001, "documents_per_step": 16, "facts_per_document": 10, "QA_per_chain_per_step": 20, "document_QA_weights": [0.8, 0.2], "learning_runs": 96, "edit_cases": 768, "edit_steps": 512, "edit_checkpoints": [0, 32, 128, 512], "edit_lr": 0.00003, "retention_kl": 1.0, "edit_scope": "mlp", "edit_mlp_layers": [3, 4, 5], "edit_batch": 128, "replay_batch": 128, "edit_weight_decay": 0.1, "E": 39, "D": 96, "R": 4096, "base_world_root": "data/bios-shortcut-confirmation-v1", "source_root": "data/bios-source", } for key, value in expected.items(): if config.get(key) != value: raise ValueError(f"Prospective confirmation contract differs: {key}") for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: raise ValueError(f"Imported E39 scientific update differs: {key}") if config.get("edit_sampling") != "shared original world932chain stream across supports": raise ValueError("The two supports retain the original paired sampling stream")
def validate_frozen_design(config_path, lock_path): config = json.loads(Path(config_path).read_text()) validate_config(config) lock = json.loads(Path(lock_path).read_text()) if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": raise ValueError("A prospective confirmation lock is required") if lock["config_sha256"] != file_hash(config_path): raise ValueError("Confirmation configuration changed after locking") if lock["sources"] != confirmation_sources(): raise ValueError("Confirmation scientific sources changed after locking") environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} if lock["environment"] != environment: raise ValueError("Confirmation numerical environment changed after locking") if not lock.get("analysis_sources"): raise ValueError("The prospective analysis implementation must also be locked") root = Path(__file__).resolve().parents[2] for relative, checksum in lock["analysis_sources"].items(): if file_hash(root / relative) != checksum: raise ValueError(f"Prospective analysis source changed: {relative}") if not lock.get("data_source_files"): raise ValueError("Original data source files must be prospectively locked") for relative, checksum in lock["data_source_files"].items(): if file_hash(root / relative) != checksum: raise ValueError(f"Original data source changed: {relative}") return config, lock
def validate_lock(config_path, lock_path, args): config, lock = validate_frozen_design(config_path, lock_path) if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") if args.world not in WORLDS or args.seed not in (0, 1): raise ValueError("Only the eight reserved worlds and two initializations are allowed") if args.phase not in PHASES or args.condition not in CONDITIONS: raise ValueError("Condition outside the prospective matrix") expected_output = ( Path(lock["output_root"]) / args.phase / "width-256" / f"world-{args.world}-seed-{args.seed}-{args.condition}" ).resolve() if Path(args.output).resolve() != expected_output: raise ValueError("Output differs from the prospective matrix") return config, lock
def validate_prepared_world(config, config_path, lock_path, world): if world not in WORLDS: raise ValueError("Requested world is outside the prospective preparation matrix") root = Path(__file__).resolve().parents[2] / config["base_world_root"] receipt = json.loads((root / "preparation-audit.json").read_text()) lock = json.loads(Path(lock_path).read_text()) if ( receipt.get("complete") is not True or receipt["config_sha256"] != file_hash(config_path) or receipt["lock_sha256"] != file_hash(lock_path) or receipt["worlds"] != list(WORLDS) ): raise ValueError("Base worlds lack a complete prospectively locked preparation") if receipt.get("source_files_sha256") != lock["data_source_files"]: raise ValueError("Prepared world source files differ from the prospective lock") filenames = ("world.npz", "metadata.json", "audit.json") expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} if set(receipt.get("files_sha256", {})) != expected_files: raise ValueError("Prepared world file manifest differs from the prospective matrix") for name in filenames: relative = f"world-{world}/{name}" if receipt["files_sha256"].get(relative) != file_hash(root / relative): raise ValueError(f"Prepared world changed: {relative}") metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) if type(metadata.get("seed")) is not int or metadata["seed"] != world: raise ValueError("Prepared world metadata seed differs from the requested world") return root, receipt
def case_identity(worker_identity, chain, support, kind, pair): payload = { "worker_identity": worker_identity, "chain": chain, "support": support, "kind": kind, "pair_contract": pair["contract"], } return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
def expected_weight_artifacts(): names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] names.append("learning/resume.pt") names.extend( f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" for support in (0, 1) for chain in CHAINS for kind in KINDS for filename in ("model-final.pt", "resume.pt") ) return names
def scientific_artifacts(output): for relative in expected_weight_artifacts(): if not (output / relative).is_file(): raise ValueError(f"Required confirmation weight artifact is missing: {relative}") paths = [output / "launch-contract.json", output / "manipulation.npz"] paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) return { str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} for p in sorted(paths) }
def run(args): config, _ = validate_lock(args.config, args.lock, args) output = Path(args.output).resolve() output.mkdir(parents=True, exist_ok=True) with (output / ".worker.lock").open("w") as handle: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) torch.set_num_threads(args.threads) base_root, data_receipt = validate_prepared_world( config, args.config, args.lock, args.world ) if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): raise ValueError("A healthy CUDA device with BF16 support is required") identity = { "protocol": PROTOCOL, "world": args.world, "seed": args.seed, "condition": args.condition, "phase": args.phase, "config_sha256": file_hash(args.config), "preregistration_lock_sha256": file_hash(args.lock), "sources": confirmation_sources(), "torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__, "device_type": "cuda", "precision": "BF16 autocast; FP32 model and optimizer", "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), "world_files_sha256": { name: checksum for name, checksum in data_receipt["files_sha256"].items() if name.startswith(f"world-{args.world}/") }, } path = output / "launch-contract.json" if path.exists() and json.loads(path.read_text()) != identity: raise ValueError("Confirmation worker identity changed") if not path.exists(): write_json(path, identity) if (output / "complete.json").exists(): return try: low = make_cross_world(args.world, source_root=base_root) high, manipulation, selected, donors = high_exception_world(low) world = low if args.phase == "low" else high pairs = { (chain, support): make_confirmation_edit_pair(low, high, chain, support) for chain in range(2) for support in (0, 1) } for chain in range(2): for key in ("groups", "E", "D", "selected_people"): if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: raise ValueError(f"The two supports overlap: {key}") atomic_numpy_save( output / "manipulation.npz", selections=selected, donors=donors, low_answers=low.answers, high_answers=high.answers, high_exceptions=high.exceptions, ) study = { **config, "confirmation_sources": identity["sources"], "phase": args.phase, "manipulation": manipulation, } learning_output = output / "learning" learning_output.mkdir(exist_ok=True) device = torch.device(args.device) model, data = learning(args, world, learning_output, study, device) with np.load(learning_output / "predictions-15360.npz") as saved: baseline_predictions = { key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") } np.testing.assert_array_equal( baseline_predictions["correct"], (baseline_predictions["prediction"] == world.answers) & baseline_predictions["ended"], ) completed = json.loads((learning_output / "learning-complete.json").read_text()) if completed["model_sha256"] != state_hash(model.state_dict()): raise ValueError("Learning baseline differs from completed weights") for chain, name in enumerate(CHAINS): arrays = autonomous_two_step(model, world, chain, device) ids = world.derived_ids[chain] arrays.update( {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} ) atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) baseline = { key: value.detach().cpu().clone() for key, value in model.state_dict().items() } identity_hash = file_hash(path) for support in (0, 1): edit_output = output / "edits" / f"support-{support}" for chain in range(2): for kind in KINDS: run_case( model, baseline, data, world, pairs[chain, support], args.phase, kind, chain, edit_output, case_identity( identity_hash, chain, support, kind, pairs[chain, support] ), baseline_predictions, device, ) write_json( output / "complete.json", { "status": "complete", "protocol": PROTOCOL, "learning_steps": 15360, "edit_cases": 8, "edit_steps": 512, "lock_sha256": file_hash(args.lock), "artifacts": scientific_artifacts(output), "finished": time.time(), }, ) except Exception as error: write_json( output / "failure.json", {"type": type(error).__name__, "message": str(error), "time": time.time()}, ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--world", type=int, required=True) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--condition", choices=CONDITIONS, required=True) parser.add_argument("--phase", choices=PHASES, required=True) parser.add_argument("--config", required=True) parser.add_argument("--lock", required=True) parser.add_argument("--output", required=True) parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Two prospectively fixed E39 supports; preparation never launches a model.
Support zero exactly preserves development selection. Support one uses aseparate deterministic stream and excludes the first support's entire groups.The original E39 audit validates both; all training and target budgets match."""
import numpy as np
from .bios_data import array_hash, rng_forfrom .bios_shortcut_control import audit_high_exceptionfrom .bios_shortcut_matched_edit import ( KINDS, PHASES, U_STRATA, audit_matched_edit_pair,)from .bios_shortcut_matched_edit import ( make_matched_edit_pair as development_pair,)
BUDGET = { "prevalence_levels": 2, "worlds": 8, "initializations": 2, "organizations": 3, "models": 96, "chains": 2, "update_types": 2, "supports_per_chain": 2, "scopes": ["mlp"], "edit_cases": 768,}
def make_confirmation_edit_pair(low, high, chain, support=0): """Three roots + 36 actual facts; same IDs and support labels across phases.
Each selected group contributes six QA-trained and six QA-heldout people who remain ordinary in the high-prevalence world. Coherent assigns all 12 to the new default. Exception assigns three default/three alternative in each split. Histograms match ACROSS all three groups, not within a group. """ if chain not in (0, 1) or support not in (0, 1): raise ValueError("Confirmation fixes two chains and two disjoint supports") if low.seed != high.seed or low.n_base != high.n_base: raise ValueError("Low/high worlds must share their identity and query layout") audit_high_exception(low, high) first = development_pair(low, high, chain) if support == 0: first["contract"].update( protocol="v2.9-shortcut-behavior-confirmation-E39", status="prospectively_fixed_confirmation_support", budget=BUDGET.copy(), model_checkpoint="width256, independent-world 15360-step low/high learning", ) return first eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) rng = rng_for(low.seed, 931, chain + 2 * support) for _ in range(10000): groups = rng.choice(eligible_groups, 3, replace=False) if len(np.unique(low.defaults[chain, groups])) == 3: break else: raise RuntimeError("Could not find three groups with distinct default cities") selected = np.empty((3, 12), dtype=np.int64) conflict = np.zeros((3, 12), dtype=bool) conflict[:, :3] = conflict[:, 6:9] = True targets = { f"{phase}_{kind}": world.answers.copy() for phase, world in (("low", low), ("high", high)) for kind in KINDS } new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] for index, group in enumerate(groups): ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] if len(eligible) != 8: raise ValueError("Expected eight still-ordinary people in each QA split") selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] actual = low.actual_ids[chain, selected[index]] derived = low.derived_ids[chain, low.memberships[chain] == group] for phase in PHASES: for kind in KINDS: target = targets[f"{phase}_{kind}"] target[low.root_ids[chain, group]] = new_default[index] target[derived] = new_default[index] target[actual] = new_default[index] if kind == "exception": target[actual[conflict[index]]] = alternative[index] edited_people = selected.ravel() selected_people = np.isin(low.memberships[chain], groups) original = selected_people & low.exceptions[chain] newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] unedited_ordinary = ( selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) ) e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) d = low.derived_ids[chain, selected_people] unchanged = np.ones(len(low.answers), dtype=bool) unchanged[np.concatenate([e, d])] = False affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) strata = np.full(len(low.answers), -1, dtype=np.int64) strata[unchanged & original_actual] = 0 strata[unchanged & newly_actual] = 1 strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 strata[unchanged & ~affected_facts & relevant] = 3 strata[unchanged & ~affected_facts & ~relevant] = 4 heldout = [] for stratum in range(5): ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) heldout = np.array(sorted(heldout), dtype=np.int64) common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) common_pool = np.setdiff1d(common_pool, heldout) if len(common_pool) < 4096: raise ValueError("Insufficient shared unchanged base facts for R4096") replay = rng.choice(common_pool, 4096, replace=False) paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) pair = { **targets, "groups": groups, "selected_people": selected, "alternative_assignments": conflict, "new_default": new_default, "alternative": alternative, "E": e, "D": d, "E_roots": low.root_ids[chain, groups], "E_actual": np.sort(low.actual_ids[chain, edited_people]), "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), "D_trained": np.intersect1d(d, low.train_ids[chain]), "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), "paired_reference_D": paired_reference, "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), "exception_conflict_D": paired_reference.copy(), "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), "D_original_exception": low.derived_ids[chain, original], "D_newly_exception": low.derived_ids[chain, newly], "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], "R": replay, "U_full": np.flatnonzero(unchanged), "U_heldout": heldout, "U_strata": strata, } for phase in PHASES: for kind in KINDS: target = targets[f"{phase}_{kind}"] actual_for_d = target[low.actual_ids[chain, selected_people]] pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] pair["contract"] = { "protocol": "v2.9-shortcut-behavior-confirmation-E39", "world": low.seed, "chain": chain, "support": support, "status": "prospectively_fixed_confirmation_support", "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), "histogram_matching_scope": ( "all three groups combined; also separately for trained/heldout QA" ), "coherent_actuals_per_group": "12 new-default (six in each QA split)", "exception_actuals_per_group": ( "6 new-default + 6 alternative (three + three in each QA split)" ), "paired_reference_semantics": ( "same 18 people; conflict only in exception, reference only in coherent" ), "R_semantics": ( "4096 identical query IDs with identical original truths " "and unchanged under all four targets" ), "U_semantics": ( "common query IDs; score each phase against its own truth and old-correct coverage" ), "U_strata": U_STRATA.copy(), "historical_E93_comparable": False, "low_truth_sha256": array_hash(low.answers), "high_truth_sha256": array_hash(high.answers), "array_sha256": {key: array_hash(value) for key, value in pair.items()}, } audit_matched_edit_pair(low, high, chain, pair) return pair123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""P3: alter shortcut reliability while preserving marginal answer counts.
The archived crossover generator and trainer are imported, never rewritten.The two chains are manipulated simultaneously; QA identities remain unchanged."""
import argparseimport fcntlimport hashlibimport jsonimport osimport timefrom dataclasses import replacefrom pathlib import Path
import numpy as npimport torch
from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedulefrom .bios_cross_train import learning, source_hashesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_organization_train import atomic_numpy_save
def high_exception_world(old): """Raise both chains from two to sixteen exceptions per 32-member group.""" audit(old) answers, exceptions = old.answers.copy(), old.exceptions.copy() selections = np.empty((2, 64, 14), dtype=np.int64) donors = np.empty((2, 14, 64), dtype=np.int64) for chain in range(2): rng = rng_for(old.seed, 930, chain) for group in range(64): ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) people = [] for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] people.extend(rng.permutation(eligible)[:7]) selections[chain, group] = people # Every lane contains one ordinary member per group. A city-deranged # bijection preserves the histogram exactly, separately in each QA split. for lane in range(14): for _ in range(10000): donor = rng.permutation(64) if np.all(old.defaults[chain, donor] != old.defaults[chain]): break else: raise RuntimeError("Could not construct a city-deranged permutation") donors[chain, lane] = donor selected = selections[chain, :, lane] answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] exceptions[chain, selected] = True world = replace(old, answers=answers, exceptions=exceptions) record = audit_high_exception(old, world) record["selection_sha256"] = array_hash(selections) record["donors_sha256"] = array_hash(donors) return world, record, selections, donors
def audit_high_exception(old, new): """Fail if the manipulation changes anything outside its declared contract.""" allowed = old.actual_ids.ravel() unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) for field in ( "prompts", "lengths", "relation", "person", "memberships", "defaults", "membership_ids", "root_ids", "actual_ids", "derived_ids", "train_ids", "heldout_ids", "city_tokens", ): np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) if old.token_labels != new.token_labels: raise ValueError("Vocabulary changed") records = [] for chain in range(2): ids = old.actual_ids[chain] np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) truth_exception = ( new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] ) np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) if np.any(old.exceptions[chain] & ~new.exceptions[chain]): raise ValueError("An original exception was removed") for group in range(64): members = new.memberships[chain] == group if int(new.exceptions[chain, members].sum()) != 16: raise ValueError("Expected sixteen exceptions per group") for pool in (new.train_ids[chain], new.heldout_ids[chain]): people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) if len(people) != 16 or new.exceptions[chain, people].sum() != 8: raise ValueError("QA split no longer has eight exceptions per group") for pool in (new.train_ids[chain], new.heldout_ids[chain]): people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) np.testing.assert_array_equal( np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) ) records.append( { "chain": chain, "old_exceptions": int(old.exceptions[chain].sum()), "new_exceptions": int(new.exceptions[chain].sum()), "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), "answer_histogram_preserved": True, "split_histograms_preserved": True, } ) for condition in CONDITIONS: np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) return { "passed": True, "world": old.seed, "old_truth_sha256": array_hash(old.answers), "new_truth_sha256": array_hash(new.answers), "prompts_sha256": array_hash(new.prompts), "chains": records, "changed_total": int((old.answers != new.answers).sum()), "document_identities_and_QA_split_preserved": True, }
def shortcut_sources(): diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") return { **source_hashes(), Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), }
def run(args): out = Path(args.output).resolve() out.mkdir(parents=True, exist_ok=True) with (out / ".lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) study = json.loads(Path(args.config).read_text()) if study["width"] != 256 or study["steps"] != 15360: raise ValueError("P3 freezes width 256 and 15360 steps") old = make_cross_world(args.world) world, manipulation, selected, donors = high_exception_world(old) contract = { "protocol": "v2.8-p3-shortcut-reliability", "study": study, "world": args.world, "seed": args.seed, "condition": args.condition, "sources": shortcut_sources(), "manipulation": manipulation, "environment": { "torch": torch.__version__, "cuda": torch.version.cuda, "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), }, } contract_path = out / "launch-contract.json" if contract_path.exists(): frozen = json.loads(contract_path.read_text()) for key in ( "protocol", "study", "world", "seed", "condition", "sources", "manipulation", ): if frozen[key] != contract[key]: raise ValueError(f"Frozen shortcut contract changed: {key}") else: write_json(contract_path, contract) atomic_numpy_save( out / "manipulation.npz", selections=selected, donors=donors, old_answers=old.answers, answers=world.answers, exceptions=world.exceptions, train_ids=world.train_ids, heldout_ids=world.heldout_ids, ) if (out / "complete.json").exists(): return # Include adapter provenance in the archived trainer's own run identity. study = {**study, "shortcut_contract": contract["sources"]} torch.set_num_threads(args.threads) try: from .bios_path_diagnostics import autonomous_two_step
device = torch.device(args.device) model, _ = learning(args, world, out, study, device) with np.load(out / f"predictions-{study['steps']}.npz") as saved: direct = {k: saved[k] for k in ("prediction", "ended", "correct")} for chain, name in enumerate(("company", "project")): arrays = autonomous_two_step(model, world, chain, device) ids = world.derived_ids[chain] arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) write_json( out / "complete.json", { "status": "complete", "phase": "P3-learning-only", "learning_steps": study["steps"], "edit_cases": 0, "finished": time.time(), }, ) except Exception as error: write_json( out / "failure.json", { "type": type(error).__name__, "message": str(error), "time": time.time(), }, ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--world", type=int, required=True) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--condition", choices=CONDITIONS, required=True) parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") parser.add_argument("--output", required=True) parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents."""
import argparseimport fcntlimport hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_cross import CHAINS, CONDITIONS, make_cross_worldfrom .bios_cross_continue import ( capture_state, edit_update, file_hash, restore_state, validate_optimizer,)from .bios_cross_train import evaluate, source_hashes, tensor_queriesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfig, select_parametersfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .bios_shortcut_control import high_exception_world, shortcut_sourcesfrom .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pairfrom .bios_train import precision
CHECKPOINTS = (0, 32, 128, 512)STUDY = { "protocol": "v2.8-p3-shortcut-matched-E39", "width": 256, "parent_step": 15360, "phases": list(PHASES), "worlds": [0, 1], "seeds": [0, 1], "conditions": list(CONDITIONS), "chains": list(CHAINS), "kinds": list(KINDS), "scope": "mlp", "mlp_layers": [3, 4, 5], "lr": 0.00003, "weight_decay": 0.1, "edit_batch": 128, "replay_batch": 128, "retention_kl": 1.0, "clip_norm": 1.0, "steps": 512, "checkpoints": list(CHECKPOINTS), "resume_every": 32, "models": 24, "edit_cases": 96, "E": 39, "D": 96, "R": 4096, "primary_reference_D": 18, "primary_reference_D_heldout": 9, "status": "prepared conditional branch; no best-step selection",}
def validate_study(study): if study != STUDY: raise ValueError("E39 editing configuration differs from the frozen prepared contract")
def editing_sources(): directory = Path(__file__).parent return { **source_hashes(), **{ name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in ( "bios_cross_continue.py", "bios_shortcut_control.py", "bios_shortcut_matched_edit.py", "bios_shortcut_edit.py", ) }, }
def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): """No phase, organization, initialization, or update-type dependence.""" rng = rng_for(world_seed, 932, chain) return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch))
def score_arrays(arrays, truth): if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): raise ValueError("Prediction shape mismatch") if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: raise ValueError("EOS and correctness must be Boolean arrays") np.testing.assert_array_equal( arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] ) return arrays
def query_metrics(correct, ids): n = len(ids) count = int(correct[ids].sum()) return {"n": n, "correct": count, "accuracy": count / n if n else None}
def retention_metrics(correct, old_correct, ids): n = len(ids) known_ids = ids[old_correct[ids]] broken = int((~correct[known_ids]).sum()) return { "n": n, "known": len(known_ids), "coverage": len(known_ids) / n if n else None, "broken": broken, "damage": broken / len(known_ids) if len(known_ids) else None, }
def edit_metrics(pair, phase, kind, arrays, old_correct): correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: raise ValueError("Old-correct coverage array mismatch") result = { key: query_metrics(correct, pair[key]) for key in ( "E", "E_roots", "E_actual", "D", "D_trained", "D_heldout", "paired_reference_D", "paired_reference_D_heldout", "D_edited_actual", "D_edited_aligned", "D_original_exception", "D_newly_exception", "D_remaining_ordinary_unedited", ) } if kind == "exception": result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) result["exception_conflict_D_heldout"] = query_metrics( correct, pair["exception_conflict_D_heldout"] ) result["factual_conflict_D"] = query_metrics( correct, pair[f"{phase}_{kind}_factual_conflict_D"] ) for pool in ("U_full", "U_heldout"): ids = pair[pool] result[pool] = { **retention_metrics(correct, old_correct, ids), "strata": { str(group): retention_metrics( correct, old_correct, ids[pair["U_strata"][ids] == group] ) for group in range(5) }, } return result
def load_parent(parent, phase): config = json.loads((parent / "config.json").read_text()) expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) if config["model"] != expected_model or config["study"]["steps"] != 15360: raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") if any( config["study"][key] != value for key, value in { "lr": 1e-4, "documents_per_step": 16, "facts_per_document": 10, "QA_per_chain_per_step": 20, "document_QA_weights": [0.8, 0.2], }.items() ): raise ValueError("E39 parent exposure or learning budget differs") if ( config["world"] not in (0, 1) or config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS ): raise ValueError("Parent is outside the fixed development matrix") if config["sources"] != source_hashes(): raise ValueError("Parent frozen trainer sources changed") if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: raise ValueError("Parent numerical software differs") if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": raise ValueError("Low parent is not an original unrestricted-context run") if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): raise ValueError("High parent manipulation/source provenance changed") low = make_cross_world(config["world"]) high, _, _, _ = high_exception_world(low) world = low if phase == "low" else high if config["truth_sha256"] != array_hash(world.answers): raise ValueError("Parent truth differs from its declared prevalence phase") with np.load(parent / "predictions-15360.npz") as saved: predictions = score_arrays( {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, world.answers, ) checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) complete = json.loads((parent / "learning-complete.json").read_text()) if ( checkpoint["step"] != 15360 or checkpoint["config"] != config["model"] or complete["status"] != "complete" ): raise ValueError("Parent learning has not completed the specified checkpoint") if state_hash(checkpoint["model"]) != complete["model_sha256"]: raise ValueError("Parent checkpoint differs from completed learning weights") provenance = { "directory": str(parent), "files_sha256": { name: file_hash(parent / name) for name in ( "config.json", "model-15360.pt", "predictions-15360.npz", "learning-complete.json", ) }, "model_sha256": complete["model_sha256"], } return config, checkpoint, predictions, low, high, world, provenance
def run_case( model, baseline, data, world, pair, phase, kind, chain, output, identity_hash, parent_predictions, device,): dest = output / f"{CHAINS[chain]}-{kind}-mlp" if (dest / "complete.json").exists(): return dest.mkdir(parents=True, exist_ok=True) model.load_state_dict(baseline) selected = select_parameters(model, "mlp", 3) e_choices, r_choices = sampling_stream(world.seed, chain) saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} saved_sets.update( old_correct=parent_predictions["correct"], edit_sampling=e_choices, replay_sampling=r_choices, ) atomic_numpy_save(dest / "sets.npz", **saved_sets) write_json(dest / "data-contract.json", pair["contract"]) target = pair[f"{phase}_{kind}"] new_data = tensor_queries(world, device, target) model.eval() references = [] with torch.no_grad(), precision(device): for begin in range(0, len(pair["R"]), 256): ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) references = torch.cat(references) optimizer = torch.optim.AdamW( selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" ) first, timeline, seconds = 0, [], 0.0 if (dest / "resume.pt").exists(): saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: raise ValueError("E39 resume identity mismatch") if not 0 <= saved["step"] <= 512 or saved["step"] % 32: raise ValueError("E39 resume step mismatch") if saved["step"]: validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) restore_state(model, optimizer, saved, device) first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] for step in range(first, 513): if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): arrays = evaluate(model, new_data, target) if step == 0: for key in ("prediction", "ended"): np.testing.assert_array_equal(arrays[key], parent_predictions[key]) point = { "step": step, "edit_seconds": seconds, **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), } timeline.append(point) atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) write_json(dest / "trajectory.json", timeline) if step % 32 == 0: atomic_torch_save( capture_state( model, optimizer, device, step=step, timeline=timeline, seconds=seconds, identity_sha256=identity_hash, case=dest.name, ), dest / "resume.pt", ) if step == 512: break ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) choices = torch.as_tensor(r_choices[step], device=device) if device.type == "cuda": torch.cuda.synchronize(device) started = time.perf_counter() edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) if device.type == "cuda": torch.cuda.synchronize(device) seconds += time.perf_counter() - started atomic_torch_save( {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, dest / "model-final.pt", ) write_json( dest / "complete.json", { "status": "complete", "phase": phase, "chain": CHAINS[chain], "kind": kind, "scope": "mlp", "final": timeline[-1], "model_sha256": state_hash(model.state_dict()), }, ) print( json.dumps( { "event": "E39_edit_complete", "case": dest.name, "E": timeline[-1]["E"]["accuracy"], "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], } ), flush=True, )
def run(args): validate_study(json.loads(Path(args.config).read_text())) parent, output = Path(args.parent).resolve(), Path(args.output).resolve() if parent == output or parent in output.parents or output in parent.parents: raise ValueError("E39 output must be separate from its immutable parent") output.mkdir(parents=True, exist_ok=True) with (output / ".lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) torch.set_num_threads(args.threads) config, checkpoint, predictions, low, high, world, provenance = load_parent( parent, args.phase ) pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] identity = { "phase": args.phase, "world": world.seed, "seed": config["seed"], "condition": config["condition"], "study": STUDY, "sources": editing_sources(), "parent": provenance, "data_contracts": [pair["contract"] for pair in pairs], "torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__, "device_type": torch.device(args.device).type, } identity_path = output / "config.json" if identity_path.exists() and json.loads(identity_path.read_text()) != identity: raise ValueError("E39 editing identity or sources changed") if not identity_path.exists(): write_json(identity_path, identity) if (output / "complete.json").exists(): return device = torch.device(args.device) if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True torch.manual_seed(config["seed"]) if device.type == "cuda": torch.cuda.manual_seed_all(config["seed"]) model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) model.load_state_dict(checkpoint["model"]) data = tensor_queries(world, device) try: baseline = { key: value.detach().cpu().clone() for key, value in model.state_dict().items() } observed = evaluate(model, data, world.answers) for key in ("prediction", "ended", "correct"): np.testing.assert_array_equal(observed[key], predictions[key]) for chain in range(2): for kind in KINDS: run_case( model, baseline, data, world, pairs[chain], args.phase, kind, chain, output, file_hash(identity_path), predictions, device, ) write_json( output / "complete.json", { "status": "complete", "phase": args.phase, "edit_cases": 4, "steps": 512, "finished": time.time(), }, ) except Exception as error: write_json( output / "failure.json", {"type": type(error).__name__, "message": str(error), "time": time.time()}, ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--parent", required=True) parser.add_argument("--phase", choices=PHASES, required=True) parser.add_argument("--output", required=True) parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents."""
import argparseimport fcntlimport hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_cross import CHAINS, CONDITIONS, make_cross_worldfrom .bios_cross_continue import ( capture_state, edit_update, file_hash, restore_state, validate_optimizer,)from .bios_cross_train import evaluate, source_hashes, tensor_queriesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfig, select_parametersfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .bios_shortcut_control import high_exception_world, shortcut_sourcesfrom .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pairfrom .bios_train import precision
CHECKPOINTS = (0, 32, 128, 512)STUDY = { "protocol": "v2.8-p3-shortcut-matched-E39", "width": 256, "parent_step": 15360, "phases": list(PHASES), "worlds": [0, 1], "seeds": [0, 1], "conditions": list(CONDITIONS), "chains": list(CHAINS), "kinds": list(KINDS), "scope": "mlp", "mlp_layers": [3, 4, 5], "lr": 0.00003, "weight_decay": 0.1, "edit_batch": 128, "replay_batch": 128, "retention_kl": 1.0, "clip_norm": 1.0, "steps": 512, "checkpoints": list(CHECKPOINTS), "resume_every": 32, "models": 24, "edit_cases": 96, "E": 39, "D": 96, "R": 4096, "primary_reference_D": 18, "primary_reference_D_heldout": 9, "status": "prepared conditional branch; no best-step selection",}
def validate_study(study): if study != STUDY: raise ValueError("E39 editing configuration differs from the frozen prepared contract")
def editing_sources(): directory = Path(__file__).parent return { **source_hashes(), **{ name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in ( "bios_cross_continue.py", "bios_shortcut_control.py", "bios_shortcut_matched_edit.py", "bios_shortcut_edit_v2.py", ) }, }
def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): """No phase, organization, initialization, or update-type dependence.""" rng = rng_for(world_seed, 932, chain) return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch))
def score_arrays(arrays, truth): if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): raise ValueError("Prediction shape mismatch") if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: raise ValueError("EOS and correctness must be Boolean arrays") np.testing.assert_array_equal( arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] ) return arrays
def query_metrics(correct, ids): n = len(ids) count = int(correct[ids].sum()) return {"n": n, "correct": count, "accuracy": count / n if n else None}
def retention_metrics(correct, old_correct, ids): n = len(ids) known_ids = ids[old_correct[ids]] broken = int((~correct[known_ids]).sum()) return { "n": n, "known": len(known_ids), "coverage": len(known_ids) / n if n else None, "broken": broken, "damage": broken / len(known_ids) if len(known_ids) else None, }
def edit_metrics(pair, phase, kind, arrays, old_correct): correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: raise ValueError("Old-correct coverage array mismatch") result = { key: query_metrics(correct, pair[key]) for key in ( "E", "E_roots", "E_actual", "D", "D_trained", "D_heldout", "paired_reference_D", "paired_reference_D_heldout", "D_edited_actual", "D_edited_aligned", "D_original_exception", "D_newly_exception", "D_remaining_ordinary_unedited", ) } if kind == "exception": result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) result["exception_conflict_D_heldout"] = query_metrics( correct, pair["exception_conflict_D_heldout"] ) result["factual_conflict_D"] = query_metrics( correct, pair[f"{phase}_{kind}_factual_conflict_D"] ) for pool in ("U_full", "U_heldout"): ids = pair[pool] result[pool] = { **retention_metrics(correct, old_correct, ids), "strata": { str(group): retention_metrics( correct, old_correct, ids[pair["U_strata"][ids] == group] ) for group in range(5) }, } return result
def load_parent(parent, phase): config = json.loads((parent / "config.json").read_text()) low = make_cross_world(config["world"]) expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) if config["model"] != expected_model or config["study"]["steps"] != 15360: raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") if any( config["study"][key] != value for key, value in { "lr": 1e-4, "documents_per_step": 16, "facts_per_document": 10, "QA_per_chain_per_step": 20, "document_QA_weights": [0.8, 0.2], }.items() ): raise ValueError("E39 parent exposure or learning budget differs") if ( config["world"] not in (0, 1) or config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS ): raise ValueError("Parent is outside the fixed development matrix") if config["sources"] != source_hashes(): raise ValueError("Parent frozen trainer sources changed") if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: raise ValueError("Parent numerical software differs") if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": raise ValueError("Low parent is not an original unrestricted-context run") if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): raise ValueError("High parent manipulation/source provenance changed") high, _, _, _ = high_exception_world(low) world = low if phase == "low" else high if config["truth_sha256"] != array_hash(world.answers): raise ValueError("Parent truth differs from its declared prevalence phase") with np.load(parent / "predictions-15360.npz") as saved: predictions = score_arrays( {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, world.answers, ) checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) complete = json.loads((parent / "learning-complete.json").read_text()) if ( checkpoint["step"] != 15360 or checkpoint["config"] != config["model"] or complete["status"] != "complete" ): raise ValueError("Parent learning has not completed the specified checkpoint") if state_hash(checkpoint["model"]) != complete["model_sha256"]: raise ValueError("Parent checkpoint differs from completed learning weights") provenance = { "directory": str(parent), "files_sha256": { name: file_hash(parent / name) for name in ( "config.json", "model-15360.pt", "predictions-15360.npz", "learning-complete.json", ) }, "model_sha256": complete["model_sha256"], } return config, checkpoint, predictions, low, high, world, provenance
def run_case( model, baseline, data, world, pair, phase, kind, chain, output, identity_hash, parent_predictions, device,): dest = output / f"{CHAINS[chain]}-{kind}-mlp" if (dest / "complete.json").exists(): return dest.mkdir(parents=True, exist_ok=True) model.load_state_dict(baseline) selected = select_parameters(model, "mlp", 3) e_choices, r_choices = sampling_stream(world.seed, chain) saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} saved_sets.update( old_correct=parent_predictions["correct"], edit_sampling=e_choices, replay_sampling=r_choices, ) atomic_numpy_save(dest / "sets.npz", **saved_sets) write_json(dest / "data-contract.json", pair["contract"]) target = pair[f"{phase}_{kind}"] new_data = tensor_queries(world, device, target) model.eval() references = [] with torch.no_grad(), precision(device): for begin in range(0, len(pair["R"]), 256): ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) references = torch.cat(references) optimizer = torch.optim.AdamW( selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" ) first, timeline, seconds = 0, [], 0.0 if (dest / "resume.pt").exists(): saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: raise ValueError("E39 resume identity mismatch") if not 0 <= saved["step"] <= 512 or saved["step"] % 32: raise ValueError("E39 resume step mismatch") if saved["step"]: validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) restore_state(model, optimizer, saved, device) first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] for step in range(first, 513): if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): arrays = evaluate(model, new_data, target) if step == 0: for key in ("prediction", "ended"): np.testing.assert_array_equal(arrays[key], parent_predictions[key]) point = { "step": step, "edit_seconds": seconds, **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), } timeline.append(point) atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) write_json(dest / "trajectory.json", timeline) if step % 32 == 0: atomic_torch_save( capture_state( model, optimizer, device, step=step, timeline=timeline, seconds=seconds, identity_sha256=identity_hash, case=dest.name, ), dest / "resume.pt", ) if step == 512: break ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) choices = torch.as_tensor(r_choices[step], device=device) if device.type == "cuda": torch.cuda.synchronize(device) started = time.perf_counter() edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) if device.type == "cuda": torch.cuda.synchronize(device) seconds += time.perf_counter() - started atomic_torch_save( {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, dest / "model-final.pt", ) write_json( dest / "complete.json", { "status": "complete", "phase": phase, "chain": CHAINS[chain], "kind": kind, "scope": "mlp", "final": timeline[-1], "model_sha256": state_hash(model.state_dict()), }, ) print( json.dumps( { "event": "E39_edit_complete", "case": dest.name, "E": timeline[-1]["E"]["accuracy"], "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], } ), flush=True, )
def run(args): validate_study(json.loads(Path(args.config).read_text())) parent, output = Path(args.parent).resolve(), Path(args.output).resolve() if parent == output or parent in output.parents or output in parent.parents: raise ValueError("E39 output must be separate from its immutable parent") output.mkdir(parents=True, exist_ok=True) with (output / ".lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) torch.set_num_threads(args.threads) config, checkpoint, predictions, low, high, world, provenance = load_parent( parent, args.phase ) pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] identity = { "phase": args.phase, "world": world.seed, "seed": config["seed"], "condition": config["condition"], "study": STUDY, "sources": editing_sources(), "parent": provenance, "data_contracts": [pair["contract"] for pair in pairs], "torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__, "device_type": torch.device(args.device).type, } identity_path = output / "config.json" if identity_path.exists() and json.loads(identity_path.read_text()) != identity: raise ValueError("E39 editing identity or sources changed") if not identity_path.exists(): write_json(identity_path, identity) if (output / "complete.json").exists(): return device = torch.device(args.device) if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True torch.manual_seed(config["seed"]) if device.type == "cuda": torch.cuda.manual_seed_all(config["seed"]) model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) model.load_state_dict(checkpoint["model"]) data = tensor_queries(world, device) try: baseline = { key: value.detach().cpu().clone() for key, value in model.state_dict().items() } observed = evaluate(model, data, world.answers) for key in ("prediction", "ended", "correct"): np.testing.assert_array_equal(observed[key], predictions[key]) for chain in range(2): for kind in KINDS: run_case( model, baseline, data, world, pairs[chain], args.phase, kind, chain, output, file_hash(identity_path), predictions, device, ) write_json( output / "complete.json", { "status": "complete", "phase": args.phase, "edit_cases": 4, "steps": 512, "finished": time.time(), }, ) except Exception as error: write_json( output / "failure.json", {"type": type(error).__name__, "message": str(error), "time": time.time()}, ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--parent", required=True) parser.add_argument("--phase", choices=PHASES, required=True) parser.add_argument("--output", required=True) parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327"""Prepared E39 update sets shared by low/high shortcut-reliability worlds.
This file generates and audits data only. It neither trains nor edits a model.The 96 proposed MLP edits are distinct from the archived E93 experiment."""
import numpy as np
from .bios_data import array_hash, rng_forfrom .bios_shortcut_control import audit_high_exception
KINDS = ("coherent", "exception")PHASES = ("low", "high")BUDGET = { "prevalence_levels": 2, "worlds": 2, "initializations": 2, "organizations": 3, "models": 24, "chains": 2, "update_types": 2, "supports_per_chain": 1, "scopes": ["mlp"], "edit_cases": 96,}U_STRATA = { "0": "original_exception_actual_in_affected_groups", "1": "newly_exception_actual_in_affected_groups", "2": "other_unchanged_facts_of_affected_people", "3": "remaining_same_chain_facts", "4": "remaining_cross_chain_or_independent_facts",}
def make_matched_edit_pair(low, high, chain, support=0): """Three roots + 36 actual facts; same IDs and support labels across phases.
Each selected group contributes six QA-trained and six QA-heldout people who remain ordinary in the high-prevalence world. Coherent assigns all 12 to the new default. Exception assigns three default/three alternative in each split. Histograms match ACROSS all three groups, not within a group. """ if chain not in (0, 1) or support != 0: raise ValueError("The prepared contract fixes two chains and support zero") if low.seed != high.seed or low.n_base != high.n_base: raise ValueError("Low/high worlds must share their identity and query layout") audit_high_exception(low, high) rng = rng_for(low.seed, 931, chain) for _ in range(10000): groups = rng.choice(64, 3, replace=False) if len(np.unique(low.defaults[chain, groups])) == 3: break else: raise RuntimeError("Could not find three groups with distinct default cities") selected = np.empty((3, 12), dtype=np.int64) conflict = np.zeros((3, 12), dtype=bool) conflict[:, :3] = conflict[:, 6:9] = True targets = { f"{phase}_{kind}": world.answers.copy() for phase, world in (("low", low), ("high", high)) for kind in KINDS } new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] for index, group in enumerate(groups): ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] if len(eligible) != 8: raise ValueError("Expected eight still-ordinary people in each QA split") selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] actual = low.actual_ids[chain, selected[index]] derived = low.derived_ids[chain, low.memberships[chain] == group] for phase in PHASES: for kind in KINDS: target = targets[f"{phase}_{kind}"] target[low.root_ids[chain, group]] = new_default[index] target[derived] = new_default[index] target[actual] = new_default[index] if kind == "exception": target[actual[conflict[index]]] = alternative[index] edited_people = selected.ravel() selected_people = np.isin(low.memberships[chain], groups) original = selected_people & low.exceptions[chain] newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] unedited_ordinary = ( selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) ) e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) d = low.derived_ids[chain, selected_people] unchanged = np.ones(len(low.answers), dtype=bool) unchanged[np.concatenate([e, d])] = False affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) strata = np.full(len(low.answers), -1, dtype=np.int64) strata[unchanged & original_actual] = 0 strata[unchanged & newly_actual] = 1 strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 strata[unchanged & ~affected_facts & relevant] = 3 strata[unchanged & ~affected_facts & ~relevant] = 4 heldout = [] for stratum in range(5): ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) heldout = np.array(sorted(heldout), dtype=np.int64) common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) common_pool = np.setdiff1d(common_pool, heldout) if len(common_pool) < 4096: raise ValueError("Insufficient shared unchanged base facts for R4096") replay = rng.choice(common_pool, 4096, replace=False) paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) pair = { **targets, "groups": groups, "selected_people": selected, "alternative_assignments": conflict, "new_default": new_default, "alternative": alternative, "E": e, "D": d, "E_roots": low.root_ids[chain, groups], "E_actual": np.sort(low.actual_ids[chain, edited_people]), "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), "D_trained": np.intersect1d(d, low.train_ids[chain]), "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), "paired_reference_D": paired_reference, "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), "exception_conflict_D": paired_reference.copy(), "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), "D_original_exception": low.derived_ids[chain, original], "D_newly_exception": low.derived_ids[chain, newly], "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], "R": replay, "U_full": np.flatnonzero(unchanged), "U_heldout": heldout, "U_strata": strata, } for phase in PHASES: for kind in KINDS: target = targets[f"{phase}_{kind}"] actual_for_d = target[low.actual_ids[chain, selected_people]] pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] pair["contract"] = { "protocol": "v2.8-p3-shortcut-matched-E39-prepared", "world": low.seed, "chain": chain, "support": support, "status": "data_only_not_executed", "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, "model_checkpoint": ( "width256, original 15360-step learning; not P2 30720-step continuation" ), "histogram_matching_scope": ( "all three groups combined; also separately for trained/heldout QA" ), "coherent_actuals_per_group": "12 new-default (six in each QA split)", "exception_actuals_per_group": ( "6 new-default + 6 alternative (three + three in each QA split)" ), "paired_reference_semantics": ( "same 18 people; conflict only in exception, reference only in coherent" ), "R_semantics": ( "4096 identical query IDs with identical original truths " "and unchanged under all four targets" ), "U_semantics": ( "common query IDs; score each phase against its own truth and old-correct coverage" ), "U_strata": U_STRATA.copy(), "historical_E93_comparable": False, "low_truth_sha256": array_hash(low.answers), "high_truth_sha256": array_hash(high.answers), "array_sha256": {key: array_hash(value) for key, value in pair.items()}, } audit_matched_edit_pair(low, high, chain, pair) return pair
def audit_matched_edit_pair(low, high, chain, pair): """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" audit_high_exception(low, high) if low.seed != high.seed or low.n_base != high.n_base: raise ValueError("Low/high world identities differ") e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: raise ValueError("E39/D96 support changed") if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: raise ValueError("Expected three groups with distinct original defaults") if selected.shape != (3, 12) or len(np.unique(selected)) != 36: raise ValueError("Expected twelve distinct people in each selected group") if high.exceptions[chain, selected].any(): raise ValueError("Selected edit people must be ordinary in both worlds") np.testing.assert_array_equal( pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] ) np.testing.assert_array_equal( pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] ) np.testing.assert_array_equal( d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] ) np.testing.assert_array_equal( e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) ) conflict = pair["alternative_assignments"] if conflict.shape != (3, 12) or conflict.dtype != np.bool_: raise ValueError("Invalid alternative assignment mask") for index, group in enumerate(groups): if not np.all(low.memberships[chain, selected[index]] == group): raise ValueError("Selected person belongs to the wrong group") for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): people = selected[index, split * 6 : (split + 1) * 6] if not np.isin(low.derived_ids[chain, people], pool).all(): raise ValueError("Selected QA split changed") if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: raise ValueError("Each group/split must have three default and three alternative") root = low.root_ids[chain, group] derived = low.derived_ids[chain, low.memberships[chain] == group] actual = low.actual_ids[chain, selected[index]] for phase in PHASES: for kind in KINDS: target = pair[f"{phase}_{kind}"] if target[root] != pair["new_default"][index] or not np.all( target[derived] == target[root] ): raise ValueError( "The three root rotations and their full propagation targets must agree" ) expected = np.full(12, target[root], dtype=np.int64) if kind == "exception": expected[conflict[index]] = pair["alternative"][index] np.testing.assert_array_equal(target[actual], expected) changed = np.union1d(e, d) for phase, world in (("low", low), ("high", high)): for kind in KINDS: target = pair[f"{phase}_{kind}"] np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) for kind in KINDS: np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) for _split, pool in ( ("all", low.derived_ids[chain]), ("trained", low.train_ids[chain]), ("heldout", low.heldout_ids[chain]), ): people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] actual = low.actual_ids[chain, people] np.testing.assert_array_equal( np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) ) reference = np.sort(low.derived_ids[chain, selected[conflict]]) np.testing.assert_array_equal(pair["paired_reference_D"], reference) np.testing.assert_array_equal(pair["exception_conflict_D"], reference) heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) if len(reference) != 18 or len(heldout_reference) != 9: raise ValueError("Expected eighteen primary exception conflicts, nine heldout") partition = [ pair[key] for key in ( "D_edited_actual", "D_original_exception", "D_newly_exception", "D_remaining_ordinary_unedited", ) ] if [len(ids) for ids in partition] != [36, 6, 42, 12]: raise ValueError("Incorrect fixed propagation strata") np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) affected = np.isin(low.memberships[chain], groups) expected_subsets = { "E_roots": low.root_ids[chain, groups], "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), "D_trained": np.intersect1d(d, low.train_ids[chain]), "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], "D_newly_exception": low.derived_ids[ chain, affected & high.exceptions[chain] & ~low.exceptions[chain] ], } for key, expected in expected_subsets.items(): np.testing.assert_array_equal(pair[key], expected) for phase in PHASES: for kind in KINDS: target = pair[f"{phase}_{kind}"] conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) u = np.setdiff1d(np.arange(len(low.answers)), changed) np.testing.assert_array_equal(pair["U_full"], u) np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) replay = pair["R"] if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): raise ValueError("R must contain 4096 unique base-fact IDs") if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: raise ValueError("Replay leaks changed support/propagation or heldout retention") if not np.isin(pair["U_heldout"], u).all(): raise ValueError("Heldout retention includes changed targets") np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) for phase in PHASES: for kind in KINDS: np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) for key, value in pair.items(): if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( value ): raise ValueError(f"Matched update array provenance changed: {key}") return { "passed": True, "E": 39, "D": 96, "exception_conflict_D": 18, "exception_conflict_D_heldout": 9, "R": 4096, "budget_edit_cases": 96, "histograms_match_across_three_groups_and_within_QA_split": True, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353"""Reproducible symbolic development trajectories for bioS-Work-v1.
Every evaluated answer is greedily generated without a correct-answer prefix.Two generated tokens is the fixed symbolic grammar budget (one value plus EOS)."""
import argparseimport hashlibimport jsonimport osimport platformimport subprocessimport timefrom contextlib import nullcontextfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_data import ( EOS, N_BASE, N_QUERIES, RELATIONS, array_hash, curriculum, load_world, write_json,)from .bios_model import CausalLM, ModelConfig, matmul_flops
def precision(device): return ( torch.autocast(device_type="cuda", dtype=torch.bfloat16) if device.type == "cuda" else nullcontext() )
def tensor_data(world, device, answers=None): answer = torch.as_tensor(world.answers if answers is None else answers, device=device) prompts = torch.as_tensor(world.prompts, device=device) lengths = torch.as_tensor(world.lengths, device=device) tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) tokens[:, :5] = prompts rows = torch.arange(N_QUERIES, device=device) tokens[rows, lengths] = answer tokens[lengths == 4, 5] = EOS positions = torch.stack([lengths - 1, lengths], dim=1) labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) return { "prompts": prompts, "lengths": lengths, "tokens": tokens, "positions": positions, "labels": labels, }
@torch.no_grad()def evaluate(model, data, world, batch_size=512, answers=None): device = data["tokens"].device targets = world.answers if answers is None else answers predictions, ended, nll = [], [], [] model.eval() for begin in range(0, N_QUERIES, batch_size): end = min(begin + batch_size, N_QUERIES) lengths = data["lengths"][begin:end] rows = torch.arange(end - begin, device=device) with precision(device): logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() first = logits.argmax(-1) continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) continuation[:, :5] = data["prompts"][begin:end] continuation[rows, lengths] = first second = model(continuation, lengths[:, None])[:, 0].argmax(-1) predictions.append(first.cpu().numpy()) ended.append(second.eq(EOS).cpu().numpy()) labels = torch.as_tensor(targets[begin:end], device=device) nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) predictions, ended, nll = ( np.concatenate(predictions), np.concatenate(ended), np.concatenate(nll), ) correct = (predictions == targets) & ended strata = { "employer": world.relation == 0, "company_default": world.relation == 1, "actual_nonexception": (world.relation == 2) & ~world.exceptions[np.maximum(world.person, 0)], "actual_old_exception": (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)], "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), } metrics = { "base_accuracy": float(correct[:N_BASE].mean()), "derived_accuracy": float(correct[N_BASE:].mean()), "value_nll": float(nll[:N_BASE].mean()), "nontermination_rate": float((~ended).mean()), "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, "learning_threshold_passed": bool( correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 ), } return metrics, { "prediction": predictions, "ended": ended, "correct": correct, "value_nll": nll, }
def code_fingerprint(): root = Path(__file__).resolve().parents[2] files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) return { "git_revision": subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=root, text=True ).strip(), "git_dirty": bool( subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() ), "source_sha256": { str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files }, }
def train(args): device = torch.device(args.device) torch.set_num_threads(args.threads) torch.manual_seed(args.seed) if device.type == "cuda": torch.cuda.manual_seed_all(args.seed) torch.backends.cuda.matmul.allow_tf32 = True world = load_world(args.world) out = Path(args.output) out.mkdir(parents=True, exist_ok=True) resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None if resume is None and (out / "config.json").exists(): raise ValueError("Output already contains a run; use a fresh output directory") schedule = curriculum(world, args.order, args.steps) model = CausalLM(ModelConfig(world.vocab_size)).to(device) data = tensor_data(world, device) optimizer = torch.optim.AdamW( model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" ) checkpoints = sorted( {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} ) config = { **vars(args), "model": model.config_dict(), "protocol": "v2.3", "phase": "development", "world_seed": world.seed, "parameters": sum(p.numel() for p in model.parameters()), "torch": torch.__version__, "python": platform.python_version(), "numpy": np.__version__, "cuda": torch.version.cuda, "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), "precision": "BF16 autocast, FP32 weights/loss/Adam moments", "checkpoints": checkpoints, "schedule_sha256": array_hash(schedule), "truth_sha256": array_hash(world.answers), "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", **code_fingerprint(), } timeline, anchors = [], {} counts = np.zeros(N_QUERIES, dtype=np.int64) weighted_exposure = np.zeros(8) train_seconds = 0.0 losses = [] steps_since_checkpoint = 0 first_step = 0 if resume is None: write_json(out / "config.json", config) np.save(out / "schedule.npy", schedule) else: # Exact continuation from the last predefined checkpoint's full training state. original = json.loads((out / "config.json").read_text()) for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): if original[key] != config[key]: raise ValueError(f"Resume mismatch on {key}") model.load_state_dict(resume["model"]) optimizer.load_state_dict(resume["optimizer"]) torch.set_rng_state(resume["torch_rng"]) if device.type == "cuda" and resume["cuda_rng"] is not None: torch.cuda.set_rng_state(resume["cuda_rng"], device) timeline, anchors = resume["timeline"], resume["anchors"] counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] train_seconds = resume["train_seconds"] first_step = resume["step"] resumes = ( json.loads((out / "resumes.json").read_text()) if (out / "resumes.json").exists() else [] ) resumes.append({"from_step": first_step, **code_fingerprint()}) write_json(out / "resumes.json", resumes) if device.type == "cuda": torch.cuda.reset_peak_memory_stats(device) for step in range(first_step, args.steps + 1): if step in checkpoints and not (resume is not None and step == first_step): start_eval = time.perf_counter() metrics, arrays = evaluate(model, data, world) for anchor, known in anchors.items(): metrics[f"forgetting_since_{anchor}"] = ( float((~arrays["correct"][known]).mean()) if known.any() else None ) if step in (2640, 5280): anchors[step] = arrays["correct"].copy() np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) # CPU state for portability; all predefined checkpoints retained. torch.save( { "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, "config": model.config_dict(), "step": step, }, out / f"model-{step}.pt", ) record = { "step": step, **metrics, "train_seconds": train_seconds, "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), "presentations": int(counts.sum()), "coverage_base": float((counts[:N_BASE] > 0).mean()), "coverage_derived": float((counts[N_BASE:] > 0).mean()), "world_tokens": int((counts * (world.lengths + 2)).sum()), "input_tokens_including_padding": step * 128 * 6, "supervised_tokens": step * 128 * 2, "lr_weighted_exposure_by_relation": dict( zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) ), "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, } timeline.append(record) write_json(out / "learning.json", timeline) print( json.dumps( { "event": "checkpoint", "step": step, "base": metrics["base_accuracy"], "derived": metrics["derived_accuracy"], "train_seconds": train_seconds, } ), flush=True, ) losses = [] steps_since_checkpoint = 0 state = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, "timeline": timeline, "anchors": anchors, "counts": counts, "weighted_exposure": weighted_exposure, "train_seconds": train_seconds, "step": step, } torch.save(state, out / "resume.pt.tmp") os.replace(out / "resume.pt.tmp", out / "resume.pt") if step == args.steps: break model.train() lr = args.lr * min((step + 1) / 2000, 1.0) for group in optimizer.param_groups: group["lr"] = lr ids_np = schedule[step] ids = torch.as_tensor(ids_np, device=device) if device.type == "cuda": torch.cuda.synchronize(device) started = time.perf_counter() optimizer.zero_grad(set_to_none=True) with precision(device): logits = model(data["tokens"][ids], data["positions"][ids]) loss = F.cross_entropy( logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) ) loss.backward() norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) if not torch.isfinite(loss) or not torch.isfinite(norm): write_json( out / "failure.json", { "step": step, "reason": "nonfinite loss or gradient", "train_seconds": train_seconds, }, ) raise FloatingPointError("Nonfinite loss or gradient") optimizer.step() if device.type == "cuda": torch.cuda.synchronize(device) train_seconds += time.perf_counter() - started losses.append(loss.item()) np.add.at(counts, ids_np, 1) weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr steps_since_checkpoint += 1 if (step + 1) % 100 == 0: print( json.dumps( { "event": "progress", "step": step + 1, "loss": float(np.mean(losses[-100:])), "train_seconds": train_seconds, } ), flush=True, ) write_json( out / "complete.json", { "step": args.steps, "status": "complete", "final": timeline[-1], "exposure_sha256": array_hash(counts), }, )
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--world", required=True) parser.add_argument("--output", required=True) parser.add_argument("--order", choices=["SA", "AS"], required=True) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--steps", type=int, default=13280) parser.add_argument("--lr", type=float, default=1e-4) parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=4) parser.add_argument("--resume", action="store_true") train(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs.
The intervention uses the original tied readout over the complete vocabulary.Only the explicitly named oracle condition accesses graph answers at inference.The wrong_entity control is an alternative to the model's decoded token, not aguaranteed incorrect answer: its accidental agreement with truth is reported."""
from __future__ import annotations
import jsonimport osimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import utc, write_jsonfrom .latent_scaling import build_world, model_digestfrom .representation_alignment import RepresentationGPT, new_modelfrom .storage_composition import data_digest, evaluate, file_hash, generate_rowsfrom .text_pretrain import WORDS, composite_sentence
CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle")
def reencode_state(state, embedding, alpha, variant="norm_matched"): """Interpolate residual and normalized embedding, without renormalizing the sum.
norm_matched gives the replacement embedding the original state's norm. paper_unit uses a unit embedding directly. Neither preserves the mixture's norm in general; alpha=0 returns the original tensor exactly. """ if not 0 <= alpha <= 1: raise ValueError("alpha must be between zero and one") if variant not in ("norm_matched", "paper_unit"): raise ValueError("Unknown re-encoding variant") if alpha == 0: return state replacement = F.normalize(embedding, dim=-1) if variant == "norm_matched": replacement = state.norm(dim=-1, keepdim=True) * replacement return (1 - alpha) * state + alpha * replacement
def alternative_entity(decoded, bridge_start, bridge_count): """A non-self bridge-entity choice, independent of the true bridge identity.""" if bridge_count < 2: raise ValueError("At least two bridge entity tokens are required") return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count)
class ReencodingGPT(RepresentationGPT): """Original computation with a single intervention at block 0, position 3."""
def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): if condition not in CONDITIONS: raise ValueError(f"Unknown condition: {condition}") if not 0 <= alpha <= 1: raise ValueError("alpha must be between zero and one") if variant not in ("norm_matched", "paper_unit"): raise ValueError("Unknown re-encoding variant") if condition == "oracle" and oracle_table is None: raise ValueError("Oracle condition requires an explicit diagnostic truth table") self.condition, self.alpha, self.variant = condition, float(alpha), variant # Deliberately outside state_dict: neither weights nor model hashes change. self.oracle_table = oracle_table if condition == "oracle" else None
def _choice(self, state, tokens): decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) selected = decoded oracle_available = torch.zeros_like(decoded, dtype=torch.bool) if self.condition == "wrong_entity": selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) elif self.condition == "oracle": oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] oracle_available = oracle >= 0 # Invalid autonomously generated heads have no graph truth. Do not # fabricate an oracle answer; retain the model's decoded token. selected = torch.where(oracle_available, oracle, decoded) return decoded, selected, oracle_available
def forward(self, tokens, positions=None, repeats=None, return_bridge=False): if not return_bridge and (self.condition == "baseline" or self.alpha == 0): return super().forward(tokens, positions=positions, repeats=repeats) if tokens.shape[1] < 4: raise ValueError("The intervention requires the causal first-relation prefix") p = self.dropout if self.training else 0.0 x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) x = F.dropout(x, p=p, training=self.training) info = None for index, block in enumerate(self.iter_blocks(repeats)): z = block.ln1(x) batch, length, width = z.shape a = block.attention q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) y = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=p, ) y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + F.dropout(y, p=p, training=self.training) x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) if index == 0: state = x[:, 3] decoded, selected, oracle_available = self._choice(state, tokens) replacement = ( state if self.condition == "baseline" else reencode_state(state, self.token(selected), self.alpha, self.variant) ) if self.condition != "baseline" and self.alpha: x = x.clone() x[:, 3] = replacement info = { "state": state, "replacement": replacement, "decoded": decoded, "selected": selected, "oracle_available": oracle_available, } x = self.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] logits = F.linear(x, self.token.weight) return (logits, info) if return_bridge else logits
def _device_settings(device): device = torch.device(device) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True if device.type == "cuda": torch.cuda.set_device(device) return device
def _load(spec, device): parent = Path(spec["parent_dir"]).resolve() checkpoint = parent / "model.pt" payload = torch.load(checkpoint, map_location="cpu", weights_only=False) model = new_model(payload["spec"], device) model.load_state_dict(payload["model"]) model.__class__ = ReencodingGPT model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] model.bridge_count = payload["spec"]["bridges_n"] model.configure("baseline", 0) model.eval().requires_grad_(False) world = dict(np.load(parent / "world.npz")) rebuilt = build_world(payload["spec"]) if data_digest(world) != data_digest(rebuilt): raise AssertionError("Saved world differs from the parent specification") oracle = torch.full( (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long ) for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): oracle[h, r] = int(target) return model, world, oracle, payload["spec"], checkpoint
@torch.no_grad()def _diagnostics(model, rows, device, batch_size): prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) collected = {} model.eval() for start in range(0, len(rows), batch_size): tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) _, info = model(tokens, return_bridge=True) values = { "decoded_bridge": info["decoded"], "selected_bridge": info["selected"], "oracle_available": info["oracle_available"], "state_norm": info["state"].norm(dim=-1), "replacement_norm": info["replacement"].norm(dim=-1), } for key, value in values.items(): collected.setdefault(key, []).append(value.cpu().numpy()) result = {key: np.concatenate(value) for key, value in collected.items()} result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) return result
def _subset_metric(correct, mask): return { "n": int(mask.sum()), "coverage": float(mask.mean()), "accuracy": float(correct[mask].mean()) if mask.any() else None, }
@torch.no_grad()def _evaluate_condition(model, world, device, batch_size): # Reuse the established complete answer/period/EOS scorer unchanged. Its # canonical batch is 512; diagnostics use the same shapes for exact decoding. if batch_size != 512: raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") metrics, predictions = evaluate(model, world, "low", device) model.eval() for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): generated = predictions[name + "_generated"] metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) metrics[name]["format_accuracy"] = float( ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() ) for name in ("familiar_test", "strict_test"): rows = world[name] info = _diagnostics(model, rows, device, batch_size) predictions.update({name + "_" + key: value for key, value in info.items()}) for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): metrics[name][key + "_coverage"] = float(info[key].mean()) if model.condition == "wrong_entity": metrics[name]["alternative_accidental_gold_match"] = float( info["selected_bridge_correct"].mean() ) correct = predictions[name + "_correct"] metrics[name]["self_bridge_correct_subset"] = _subset_metric( correct, info["decoded_bridge_correct"] ) first = rows[:, [0, 1, 2]] second = rows[:, [2, 3, 4]] for role, atoms in (("first", first), ("second", second)): _, raw = generate_rows(model, atoms, device, batch_size=batch_size) predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) autonomous_second = second.copy() autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) return metrics, predictions
def cases(spec): """One baseline and the frozen alpha/variant/condition matrix.""" conditions = list(spec.get("conditions", CONDITIONS)) if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): raise ValueError("Conditions must be distinct known names") alphas = spec.get("alphas", [spec.get("alpha", 0)]) variants = spec.get("variants", ["norm_matched"]) if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): raise ValueError("alphas must contain distinct values in [0,1]") if len(variants) != len(set(variants)) or not variants: raise ValueError("variants must be distinct and nonempty") if any(v not in ("norm_matched", "paper_unit") for v in variants): raise ValueError("Unknown re-encoding variant") matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} for variant in variants: for alpha in alphas: for condition in conditions: if condition == "baseline": continue name = f"{variant}-a{float(alpha):g}-{condition}" matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} return matrix
def _evaluate_all(model, world, oracle, spec, callback=None): matrix = cases(spec) metrics, arrays = {}, {} for name, case in matrix.items(): model.configure( case["condition"], case["alpha"], oracle if case["condition"] == "oracle" else None, case["variant"], ) metrics[name], predictions = _evaluate_condition( model, world, next(model.parameters()).device, spec.get("batch_size", 512) ) arrays.update({name + "__" + key: value for key, value in predictions.items()}) if callback is not None: callback(name, case, metrics[name], predictions) for name in ("familiar_test", "strict_test"): baseline = arrays[f"baseline__{name}_coverage"] # This is the fixed pre-intervention prerequisite pool for every case. # In particular, the destructive alternative-entity control cannot # determine which chains enter the main conditional comparison. arrays[f"common__{name}_atomic_correct"] = baseline for condition in matrix: correct = arrays[f"{condition}__{name}_correct"] arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( correct, baseline ) self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] joint = baseline & self_ok arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( correct, joint ) model.configure("baseline", 0) return metrics, arrays
def run(spec, out, device="cuda:2"): """Evaluate one existing checkpoint; never train or overwrite an attempt.""" out = Path(out) if (out / "run.json").exists(): raise FileExistsError(f"Do not overwrite an attempt: {out}") out.mkdir(parents=True, exist_ok=True) device = _device_settings(device) started = time.perf_counter() model, world, oracle, parent_spec, checkpoint = _load(spec, device) digest = model_digest(model) source = { str(Path(__file__).resolve()): file_hash(__file__), "parent_checkpoint": file_hash(checkpoint), } manifest = { "spec": spec, "parent_spec": parent_spec, "source": source, "world_sha256": data_digest(world), "model_sha256": digest, "pid": os.getpid(), "device": str(device), "started_utc": utc(), "new_training_updates": 0, "optimizer_updates": 0, "cases": cases(spec), "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", "decoder": "original ln_final and tied output, argmax over the full vocabulary", "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", "bridge_token_start": model.bridge_start, "bridge_token_count": model.bridge_count, "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", "alpha_zero_exact_bypass": True, "allow_tf32": True, } write_json(out / "run.json", manifest) np.savez_compressed(out / "world.npz", **world) history = []
def record(name, case, metrics, predictions): history.append( { "step": len(history) + 1, "case": name, **case, "metrics": metrics, "optimizer_updates": 0, "wall_seconds": time.perf_counter() - started, "created_utc": utc(), } ) # Each condition is durable before the next one starts. np.savez_compressed(out / f"predictions-{name}.npz", **predictions) write_json(out / "learning.json", history) write_json( out / "status.json", { "state": "running", "step": len(history), "budget": len(manifest["cases"]), "optimizer_updates": 0, }, )
metrics, predictions = _evaluate_all(model, world, oracle, spec, record) assert model_digest(model) == digest, "Evaluation changed model parameters" # Final common-prerequisite subsets are known only after the full matrix. write_json(out / "learning.json", history) # At zero weight all conditions must recover complete baseline generation. for key, value in predictions.items(): if key.endswith(("_generated", "_answer_nll")): case, suffix = key.split("__", 1) if manifest["cases"][case]["alpha"] == 0: np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) np.savez_compressed(out / "predictions.npz", **predictions) write_json(out / "metrics.json", metrics) result = { "state": "evaluation-complete-awaiting-independent-audit", "finished_utc": utc(), "wall_seconds": time.perf_counter() - started, "model_sha256": digest, "new_training_updates": 0, "optimizer_updates": 0, "conditions": list(metrics), "prediction_arrays": len(predictions), "step": len(history), } write_json(out / "evaluation-complete.json", result) write_json(out / "status.json", {**result, "step": len(history)}) return result
def audit(out, device="cuda:2"): """Reload weights and independently recompute every saved prediction array.""" out = Path(out) device = _device_settings(device) manifest = json.loads((out / "run.json").read_text()) model, world, oracle, _, checkpoint = _load(manifest["spec"], device) assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] assert model_digest(model) == manifest["model_sha256"] assert data_digest(world) == manifest["world_sha256"] metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) saved = dict(np.load(out / "predictions.npz")) assert set(saved) == set(actual), "Prediction array set changed" max_error = 0.0 for key, value in actual.items(): if value.dtype.kind == "f": max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) else: np.testing.assert_array_equal(value, saved[key]) # Recount complete-answer accuracy independently of the established scorer. for condition, groups in metrics.items(): for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): pred = actual[f"{condition}__{name}_generated"] correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) assert float(correct.mean()) == groups[name]["accuracy"] assert model_digest(model) == manifest["model_sha256"] result = { "passed": True, "independently_reloaded": True, "raw_predictions_recounted": True, "prediction_arrays": len(actual), "max_float_error": max_error, "audit_pid": os.getpid(), "independent_process": os.getpid() != manifest["pid"], "finished_utc": utc(), "metrics": metrics, } write_json(out / "audit.json", result) complete = json.loads((out / "evaluation-complete.json").read_text()) complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) write_json(out / "complete.json", complete) write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) return result12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112"""Causal entity-coordinate interventions using an averaged prefix Jacobian.
This is a restricted adaptation of Anthropic's Jacobian lens: calibration anddonors contain only the first fact's query prefix. No relation suffix or answergradient is used to construct a direction. Execution layers count shared blockoccurrences separately. All model parameters remain frozen."""
from __future__ import annotations
import hashlibimport jsonimport osimport timefrom collections import defaultdictfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import utc, write_jsonfrom .latent_scaling import model_digestfrom .storage_composition import file_hash
SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back")ERASURES = ( "erase_state", "erase_mlp", "erase_attention", "random_state", "random_mlp", "random_attention", "restore_mlp", "fixed_entity_mlp", "fixed_entity_random_mlp",)
class ModelView: """Expose native attention/MLP increments without replacing trained modules."""
def __init__(self, model): if model.training: raise ValueError("Interventions require eval mode") self.model = model self.large = hasattr(model, "transformer") if self.large: t = model.transformer self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f self.blocks = list(t.h) * model.repeats self.heads = model.config.n_head else: self.embedding, self.position, self.norm = model.token, model.position, model.ln_final self.blocks = list(model.iter_blocks()) self.heads = model.config.heads self.width = self.embedding.weight.shape[1] self.device = self.embedding.weight.device
def embed(self, tokens): return self.embedding(tokens) + self.position( torch.arange(tokens.shape[1], device=self.device) )
def parts(self, x, block, *, math_attention=False): if self.large: z = block.ln_1(x) q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) project, ln2 = block.attn.c_proj, block.ln_2 else: z = block.ln1(x) q, k, v = block.attention.qkv(z).chunk(3, dim=-1) project, ln2 = block.attention.proj, block.ln2 shape = (len(x), x.shape[1], self.heads, self.width // self.heads) q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) if math_attention: # The explicit FP32 expression permits batched VJPs on torch 2.6. scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v else: y = F.scaled_dot_product_attention(q, k, v, is_causal=True) attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) after_attention = x + attention mlp = block.mlp(ln2(after_attention)) return after_attention + mlp, attention, mlp
def hidden( self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False ): x, states, attentions, mlps = self.embed(tokens), [], [], [] for index, block in enumerate(self.blocks): x, attention, mlp = self.parts(x, block, math_attention=math_attention) if capture: states.append(x[:, sender].detach()) attentions.append(attention[:, sender].detach()) mlps.append(mlp[:, sender].detach()) if index == layer: if sender is None or delta is None or delta.shape != x[:, sender].shape: raise ValueError("A patch requires one delta per example at a fixed sender") mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) x = x + mask[None, :, None] * delta[:, None, :] if capture: return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) return x
def logits(self, tokens, **patch): return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight)
def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): """E[d h_final,sender / d h_layer,sender], with labels absent from the graph.
A shared shift applied to all independent calibration prompts differentiates their mean output, exactly averaging their Jacobians. Parameters need no gradients. The endpoint is the residual before the final LayerNorm. """ if any(p.requires_grad for p in view.model.parameters()): raise ValueError("Freeze model parameters before constructing the lens") with torch.no_grad(): x, boundaries = view.embed(prefixes), [] for block in view.blocks: x, _, _ = view.parts(x, block, math_attention=True) boundaries.append(x.detach()) jacobians = [] identity = torch.eye(view.width, device=view.device) for layer, boundary in enumerate(boundaries): shift = torch.zeros(view.width, device=view.device, requires_grad=True) mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() x = boundary + mask[None, :, None] * shift[None, None, :] for block in view.blocks[layer + 1 :]: x, _, _ = view.parts(x, block, math_attention=True) endpoint = x[:, sender].mean(0) rows = [] for start in range(0, view.width, chunk): rows.append( torch.autograd.grad( endpoint, shift, grad_outputs=identity[start : start + chunk], is_grads_batched=True, retain_graph=start + chunk < view.width, )[0].detach() ) jacobians.append(torch.cat(rows)) return torch.stack(jacobians)
def swap_coordinates(state, basis): """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" if basis.shape != (*state.shape, 2): raise ValueError("Expected [example, width, two semantic axes]") coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) difference = coefficients.flip(-1) - coefficients return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype)
def projection(state, direction): direction = F.normalize(direction, dim=-1) return (state * direction).sum(-1, keepdim=True) * direction
def match_norm(delta, reference): norm = delta.norm(dim=-1, keepdim=True) if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): raise ValueError("Degenerate random control") return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12)
def control_observation(changed, baseline): """Record numerical control outcomes without silently dropping sensitive cases.""" mask = np.any(changed != baseline, axis=1) return { "n_queries": len(baseline), "generated_rows_changed": int(mask.sum()), "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), "changed_query_indices": np.flatnonzero(mask).tolist(), "changed_fraction": float(mask.mean()), "exact": bool(not mask.any()), }
def _rank(seed, *values): return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest()
def select_pairs(atoms, first_families, seed, per_family, *, ood=None): """Choose prefixes/donors and all shared continuations using graph truth only.
Donors use the same r1 and first-fact family. Every pair has at least two distinct shared r2 with different original/counterfactual tails. A pair is selected before scoring; its exact same prefix intervention serves every r2. """ atoms = np.asarray(atoms, dtype=np.int64) outgoing, relation = defaultdict(dict), defaultdict(list) for index, (head, r, tail) in enumerate(atoms): if int(r) in outgoing[int(head)]: raise ValueError("Ambiguous atomic truth") outgoing[int(head)][int(r)] = (int(tail), index) relation[int(r)].append(index) groups, queries, coverage = [], [], {} for name, indices in first_families.items(): allowed = set(map(int, indices)) eligible = [] for first in sorted(allowed): head, r1, bridge = map(int, atoms[first]) candidates = [] for donor in relation[r1]: dh, _, db = map(int, atoms[donor]) if donor not in allowed or dh == head or db == bridge: continue common = sorted(set(outgoing[bridge]) & set(outgoing[db])) common = [ r for r in common if outgoing[bridge][r][0] != outgoing[db][r][0] and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} ] if len(common) >= 2: candidates.append((donor, common)) if candidates: donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) eligible.append((first, donor, common)) eligible.sort(key=lambda v: _rank(seed, v[0])) coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} for first, donor, common in eligible[:per_family]: head, r1, bridge = map(int, atoms[first]) dh, _, db = map(int, atoms[donor]) group = len(groups) groups.append([head, r1, bridge, dh, db, first, donor]) for r2 in common: tail, second = outgoing[bridge][r2] ct, cf_second = outgoing[db][r2] kind = ( name if ood is None else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") ) queries.append((group, r2, tail, ct, second, cf_second, kind)) coverage[name]["selected"] = min(len(eligible), per_family) if not groups: raise ValueError("No graph-eligible cross-relation pairs; do not reroll") return { "groups": np.asarray(groups, dtype=np.int64), "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), "strata": np.asarray([r[6] for r in queries]), "counterfactual_strata": np.asarray( [ r[6] if ood is None else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") for r in queries ] ), "coverage": coverage, }
def prefixes(facts, large, metadata): facts = np.asarray(facts) if large: return np.column_stack( (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) ) return np.column_stack( (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) )
def prompts(rows, large, metadata): if large: from .grokking_reproduction import encode_rows
return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] from .text_pretrain import atomic_sentence, composite_sentence
render = atomic_sentence if rows.shape[1] == 3 else composite_sentence length = 5 if rows.shape[1] == 3 else 7 return np.asarray([render(row)[:length] for row in rows])
def query_training_masks(world, payload, groups, queries, large): """Count composition exposure without using scores or answer correctness.""" if large: support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) trained = world["chains"][world["train_order"][:support]][:, :3] else: trained = world["train_composite"][:, [0, 1, 3]] trained = set(map(tuple, trained)) recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) return { "recipient_query_trained": recipient, "counterfactual_query_trained": donor, "both_queries_untrained": ~recipient & ~donor, }
def load_task(spec, device): payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) if "checkpoint_step" in spec: saved_step = payload.get("step", payload["spec"].get("steps")) assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" if spec["family"] == "reproduction": from .grokking_reproduction import construct
data = Path(spec["data"]) metadata = json.loads((data / "complete.json").read_text()) model = construct(payload["spec"], metadata, device) world = dict(np.load(data / "world.npz")) panels = dict(np.load(data / "panels.npz")) atoms = world["atoms"].astype(np.int64) families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} ood = world["ood"] entities = np.arange( metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] ) else: from .representation_alignment import new_model
model = new_model(payload["spec"], device) world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) metadata = {"entity_offset": 0} atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) families = {} for name in ("familiar_test", "strict_test"): firsts = set(map(tuple, world[name][:, :3])) families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) ood = None entities = np.arange(21, model.config.vocab_size) panels = {k: world[k] for k in ("familiar_test", "strict_test")} model.load_state_dict(payload["model"]) model.eval().requires_grad_(False) return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels
@torch.no_grad()def trace_in_batches(view, tokens, sender, batch_size, amp): collected = [] for start in range(0, len(tokens), batch_size): batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): _, trace = view.hidden(batch, sender=sender, capture=True) collected.append(tuple(a.float() for a in trace)) return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3))
@torch.no_grad()def generate( view, tokens, targets, counterfactual, metadata, batch_size, *, layer=None, sender=None, delta=None,): """Greedy generation with feedback; scoring retains both target probabilities.""" offset = metadata["entity_offset"] targets, counterfactual = targets + offset, counterfactual + offset generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] for start in range(0, len(tokens), batch_size): x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) patch = ( {} if layer is None else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} ) draws = [] for index in range(2 if view.large else 3): with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): logits = view.logits(x, **patch).float() if index == 0: logs = logits.log_softmax(-1) arange = torch.arange(len(x), device=view.device) original_logp.append( logs[ arange, torch.as_tensor(targets[start : start + batch_size], device=view.device), ] .cpu() .numpy() ) cf_logp.append( logs[ arange, torch.as_tensor( counterfactual[start : start + batch_size], device=view.device ), ] .cpu() .numpy() ) scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) top_ids.append(ids.cpu().numpy()) top_scores.append(scores.cpu().numpy()) answer = logits.argmax(-1) draws.append(answer.cpu().numpy()) x = torch.cat((x, answer[:, None]), dim=1) generated.append(np.stack(draws, axis=1)) return { "generated": np.concatenate(generated), "original_logp": np.concatenate(original_logp), "cf_logp": np.concatenate(cf_logp), "top_ids": np.concatenate(top_ids), "top_logp": np.concatenate(top_scores), }
def summarize(result, targets, counterfactual, metadata, strata, groups=None): generated = result["generated"] original = generated[:, 0] == targets + metadata["entity_offset"] cf = generated[:, 0] == counterfactual + metadata["entity_offset"] format_ok = ( generated[:, 1] == metadata["end_marker"] if "end_marker" in metadata else (generated[:, 1] == 5) & (generated[:, 2] == 1) ) output = {} for name in ("all", *sorted(set(strata))): mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name row = { "n_queries": int(mask.sum()), "answer_accuracy": float(original[mask].mean()), "accuracy": float((original & format_ok)[mask].mean()), "cf_answer_accuracy": float(cf[mask].mean()), "cf_accuracy": float((cf & format_ok)[mask].mean()), "format_accuracy": float(format_ok[mask].mean()), "answer_nll": float(-result["original_logp"][mask].mean()), "cf_nll": float(-result["cf_logp"][mask].mean()), } if groups is not None: unique = np.unique(groups[mask]) row["n_first_facts"] = len(unique) row["all_relations_cf_accuracy"] = float( np.mean([cf[mask & (groups == g)].all() for g in unique]) ) row["mean_first_fact_cf_accuracy"] = float( np.mean([cf[mask & (groups == g)].mean() for g in unique]) ) output[name] = row return output
def run(spec, settings, out, gpu): """Run one checkpoint with all execution layers, including failed interventions.""" out = Path(out) out.mkdir(parents=True, exist_ok=True) if (out / "run.json").exists(): raise FileExistsError(f"Do not overwrite an attempt: {out}") torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.cuda.set_device(gpu) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True device = torch.device(f"cuda:{gpu}") began = time.perf_counter() view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) digest_before = model_digest(view.model) write_json( out / "run.json", { "spec": { **spec, "settings": settings, "checkpoint_step": payload.get("step", payload["spec"].get("steps")), }, "checkpoint_sha256": file_hash(spec["checkpoint"]), "initial_model_sha256": digest_before, "world_sha256": file_hash(Path(spec["data"]) / "world.npz") if view.large else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), "job_type": "causal-intervention", "pid": os.getpid(), "gpu": gpu, "gpu_name": torch.cuda.get_device_name(gpu), "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", "parameters": sum(p.numel() for p in view.model.parameters()), "vocab_size": len(view.embedding.weight), "tags": ["bridge-workspace", spec["phase"], "no-training"], "created_utc": utc(), }, ) history, cursor = [], 0
def log(stage, metrics): nonlocal cursor history.append( { "step": cursor, "metrics": metrics, "wall_seconds": time.perf_counter() - began, "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), } ) write_json(out / "learning.json", history) write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) print( json.dumps( { "run": spec["name"], "stage": stage, "index": cursor, "wall_seconds": history[-1]["wall_seconds"], } ), flush=True, ) cursor += 1
log("loaded", {}) pairs = select_pairs( atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood ) groups, q = pairs["groups"], pairs["queries"] used_first = set(groups[:, 5]) | set(groups[:, 6]) calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ : settings["calibration_prompts"] ] sender = 1 if view.large else 3 cp = prefixes(atoms[calibration], view.large, metadata) tensors = torch.as_tensor(cp, device=device) jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) torch.save( {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, out / "lens.pt", ) log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) trace = trace_in_batches( view, prefixes(groups[:, :3], view.large, metadata), sender, settings["batch_size"], view.large, ) donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) donor_states = trace_in_batches( view, prefixes(donor_facts, view.large, metadata), sender, settings["batch_size"], view.large, )[0] rows = ( np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) if view.large else np.column_stack( (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) ) ) tokens = prompts(rows, view.large, metadata) training_masks = query_training_masks(world, payload, groups, q, view.large) # Fix a native panel per stratum without consulting any predictions. native_rows, native_strata = [], [] for name in ( ("test_ii", "test_io", "test_oi", "test_oo") if view.large else ("familiar_test", "strict_test") ): selected = panels[name][: settings["native_per_stratum"]] native_rows.append(selected) native_strata.extend([name] * len(selected)) native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) fixed_entity = int(unique_bridges[bridge_counts.argmax()]) fixed_target = native_facts[:, 2] == fixed_entity ntokens = prompts(native_rows, view.large, metadata) ntrace = trace_in_batches( view, prefixes(native_facts, view.large, metadata), sender, settings["batch_size"], view.large, ) all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) for row, fact in zip(native_rows, native_facts, strict=True): r2 = row[2] if view.large else row[3] all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) all_needed.add(lookup[int(fact[2]), int(r2)][1]) needed_ids = np.asarray(sorted(all_needed)) needed = atoms[needed_ids] atrace = trace_in_batches( view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large ) torch.save( { "recipient": tuple(a.cpu() for a in trace), "donor_states": donor_states.cpu(), "native": tuple(a.cpu() for a in ntrace), "atomic": tuple(a.cpu() for a in atrace), }, out / "prefix-traces.pt", ) atomic = generate( view, prompts(needed, view.large, metadata), needed[:, -1], needed[:, -1], metadata, settings["batch_size"], ) atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) prereq = np.asarray( [ all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) for g, _, _, _, second, cf_second in q ] ) np.savez_compressed( out / "selection.npz", **{k: v for k, v in pairs.items() if k != "coverage"}, rows=rows, native_rows=native_rows, native_strata=native_strata, fixed_entity=np.asarray(fixed_entity), fixed_entity_target=fixed_target, **training_masks, prerequisite_correct=prereq, needed_atomic_indices=needed_ids, **{"atomic_" + k: v for k, v in atomic.items()}, ) write_json(out / "coverage.json", pairs["coverage"]) # Independent native implementation equivalence and prefix-causality audit. audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): native = view.model( audit_tokens, positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), )[:, 0].float() traced = view.logits(audit_tokens).float() _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) causal_error = float( (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() ) torch.testing.assert_close( full_trace[0].float(), trace[0][:, q[: len(audit_tokens), 0]], atol=0.05 if view.large else 2e-5, rtol=0.005 if view.large else 2e-5, ) torch.testing.assert_close( native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 ) if not torch.equal(native.argmax(-1), traced.argmax(-1)): raise AssertionError("Native/traced greedy answers differ") summary = {}
def measure( family, condition, layer, input_tokens, target, cf_target, strata, delta=None, query_groups=None, ): result = generate( view, input_tokens, target, cf_target, metadata, settings["batch_size"], layer=layer if delta is not None else None, sender=sender, delta=delta, ) np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) metrics = summarize(result, target, cf_target, metadata, strata, query_groups) if family == "swap" and prereq.any(): metrics["prerequisites_correct"] = summarize( {k: a[prereq] for k, a in result.items()}, target[prereq], cf_target[prereq], metadata, strata[prereq], query_groups[prereq], )["all"] if family == "swap" and training_masks["both_queries_untrained"].any(): mask = training_masks["both_queries_untrained"] metrics["both_queries_untrained"] = summarize( {k: a[mask] for k, a in result.items()}, target[mask], cf_target[mask], metadata, strata[mask], query_groups[mask], )["all"] if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): for label, mask in ( ("fixed_entity_target", fixed_target), ("fixed_entity_unrelated", ~fixed_target), ): if mask.any(): metrics[label] = summarize( {k: a[mask] for k, a in result.items()}, target[mask], cf_target[mask], metadata, strata[mask], )["all"] summary[f"{family}/{condition}/{layer}"] = metrics write_json(out / "summary.json", summary) log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}})
measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) measure( "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata ) measure( "atomic", "baseline", -1, prompts(needed, view.large, metadata), needed[:, -1], needed[:, -1], np.full(len(needed), "needed_atoms"), ) states, attentions, mlps = trace rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) swap_errors, restore_errors = [], [] diagnostics = [] axis_families = settings.get("axis_families", ["prefix_jacobian"]) if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: raise ValueError("Unknown direction family") for layer, jacobian, axis_family in ( (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families ): suffix = "_embedding" if axis_family == "input_embedding" else "" directions = F.normalize( view.embedding.weight[torch.as_tensor(entities, device=device)].float() @ (torch.eye(view.width, device=device) if suffix else jacobian), dim=-1, ) index = {int(e): i for i, e in enumerate(entities)} source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] basis = torch.stack((source, dest), dim=-1) swapped = swap_coordinates(states[layer], basis) restored = swap_coordinates(swapped, basis) swap_errors.append(float((restored - states[layer]).abs().max())) random_basis = rotation[None] @ basis swap_delta = swapped - states[layer] torch.save( { "basis": basis.cpu(), "rotation": rotation.cpu(), "swap_delta": swap_delta.cpu(), "axis_family": axis_family, }, out / f"patch-{axis_family}-l{layer:02d}.pt", ) deltas = { "swap": swap_delta, "swap_x2": 2 * swap_delta, "random_swap": match_norm( swap_coordinates(states[layer], random_basis) - states[layer], swap_delta ), "full_prefix": donor_states[layer] - states[layer], "swap_back": restored - states[layer], } for condition in SWAPS: measure( "swap", condition + suffix, layer, tokens, q[:, 2], q[:, 3], pairs["strata"], deltas[condition][q[:, 0]], q[:, 0], ) native_direction = directions[ [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] ] native_state, native_attention, native_mlp = (a[layer] for a in ntrace) fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ None ].expand_as(native_direction) fixed_mlp = projection(native_mlp, fixed_direction) removed_mlp = projection(native_mlp, native_direction) # All sublayers still execute. Only the selected sender's semantic component # is subtracted from the actual local update at the boundary. local_restore = native_state - removed_mlp + removed_mlp restore_errors.append(float((local_restore - native_state).abs().max())) erasures = { "erase_state": -projection(native_state, native_direction), "erase_mlp": -removed_mlp, "erase_attention": -projection(native_attention, native_direction), "random_state": match_norm( -projection(native_state, native_direction @ rotation.T), -projection(native_state, native_direction), ), "random_mlp": match_norm( -projection(native_mlp, native_direction @ rotation.T), -removed_mlp ), "random_attention": match_norm( -projection(native_attention, native_direction @ rotation.T), -projection(native_attention, native_direction), ), "restore_mlp": local_restore - native_state, "fixed_entity_mlp": -fixed_mlp, "fixed_entity_random_mlp": match_norm( -projection(native_mlp, fixed_direction @ rotation.T), -fixed_mlp, ), } for condition in ERASURES: measure( "native", condition + suffix, layer, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata, erasures[condition], ) # Relevant single-hop facts are scored under exactly the same local deletion. adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] atomic_delta = -projection(atrace[2][layer], adirection) measure( "atomic", "erase_mlp" + suffix, layer, prompts(needed, view.large, metadata), needed[:, -1], needed[:, -1], np.full(len(needed), "needed_atoms"), atomic_delta, ) with torch.no_grad(): raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) diagnostics.append( { "layer": layer, "axis_family": axis_family, "native_bridge_readout_accuracy": float( ( raw == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) ) .float() .mean() ), "prefix_jacobian_bridge_readout_accuracy": float( ( lens == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) ) .float() .mean() ), "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), } ) digest_after = model_digest(view.model) if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): raise AssertionError("Intervention changed model parameters or accumulated gradients") write_json( out / "implementation-audit.json", { "parameters_unchanged": True, "native_tracer_max_logit_error": float((native - traced).abs().max()), "prefix_causal_state_max_error": causal_error, "swap_inverse_max_errors": swap_errors, "mlp_restore_max_errors": restore_errors, "n_needed_atomic_facts": len(needed), "needed_atomic_answer_accuracy": float(atomic_ok.mean()), "swap_prerequisite_query_coverage": float(prereq.mean()), "scoring": ( "greedy feedback, original/counterfactual answer plus termination; " "query and first-fact denominators separate" ), }, ) write_json(out / "diagnostics.json", diagnostics) log("complete", {"complete": {"evaluations": len(summary)}}) write_json( out / "interventions-complete.json", { "finished_utc": utc(), "evaluations": len(summary), "model_sha256": digest_after, "wall_seconds": time.perf_counter() - began, "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), "new_training_updates": 0, }, ) write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1})
def audit_run(out, gpu): """Reload in an independent process and reproduce fixed raw prediction subsets.""" out = Path(out) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.cuda.set_device(gpu) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True metadata_run = json.loads((out / "run.json").read_text()) spec = metadata_run["spec"] settings = spec["settings"] view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") assert model_digest(view.model) == metadata_run["initial_model_sha256"] assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" selection = dict(np.load(out / "selection.npz")) groups, queries = selection["groups"], selection["queries"] jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ "jacobians" ] sender = 1 if view.large else 3 trace = trace_in_batches( view, prefixes(groups[:, :3], view.large, metadata), sender, settings["batch_size"], view.large, ) states = trace[0] native_rows = selection["native_rows"] lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) ntrace = trace_in_batches( view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large ) swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) native_indices = np.unique( np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) ) summary = json.loads((out / "summary.json").read_text()) comparisons, max_logp_error, identity_controls = [], 0.0, []
def check(family, condition, layer, indices, rows, target, cf, delta=None): nonlocal max_logp_error
# Baseline is independently executed through the model's own forward. class NativeView(ModelView): def logits(self, tokens, **_): positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) return self.model(tokens, positions=positions)[:, 0]
actual = generate( NativeView(view.model) if condition == "baseline" else view, prompts(rows, view.large, metadata), target, cf, metadata, settings["batch_size"], layer=layer if delta is not None else None, sender=sender, delta=delta, ) # Preserve original batch shapes: compacting selected rows changes BF16 # GEMM rounding. Select the audit subset only after the full generation. actual = {key: value[indices] for key, value in actual.items()} expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) if not np.array_equal(actual["generated"], expected["generated"][indices]): raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") for key in ("original_logp", "cf_logp"): error = float(np.max(np.abs(actual[key] - expected[key][indices]))) max_logp_error = max(max_logp_error, error) np.testing.assert_allclose( actual[key], expected[key][indices], atol=0.04 if view.large else 3e-5, rtol=0.002 if view.large else 2e-5, ) comparisons.append( {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} )
check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) check( "native", "baseline", -1, native_indices, native_rows, native_rows[:, -1], native_rows[:, -1], ) entity_index = {int(e): i for i, e in enumerate(entities)} for layer, jacobian in enumerate(jacobians): for axis_family in settings.get("axis_families", ["prefix_jacobian"]): suffix = "_embedding" if axis_family == "input_embedding" else "" directions = F.normalize( view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() @ (torch.eye(view.width, device=view.device) if suffix else jacobian), dim=-1, ) source = directions[ [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] ] dest = directions[ [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] ] delta = ( swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] ) check( "swap", "swap" + suffix, layer, swap_indices, selection["rows"], queries[:, 2], queries[:, 3], delta[queries[:, 0]], ) native_direction = directions[ [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] ] native_delta = -projection(ntrace[2][layer], native_direction) check( "native", "erase_mlp" + suffix, layer, native_indices, native_rows, native_rows[:, -1], native_rows[:, -1], native_delta, ) # Structural and numerical controls must retain native generation. for family, condition in ( ("swap", "swap_back" + suffix), ("native", "restore_mlp" + suffix), ): raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] identity_controls.append( { "family": family, "condition": condition, "layer": layer, **control_observation(raw, baseline), } ) if layer == len(view.blocks) - 1: for key in summary: family, condition, occurrence = key.split("/") if int(occurrence) != layer or family == "atomic": continue raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] assert np.array_equal(raw, baseline), ( key, "final sender must not affect later positions", ) assert model_digest(view.model) == metadata_run["initial_model_sha256"] previous = out / "implementation-audit.json" if not previous.exists() and (out / "audit.json").exists(): previous.write_bytes((out / "audit.json").read_bytes()) write_json( out / "audit.json", { "independent_process": True, "pid": os.getpid(), "gpu": gpu, "finished_utc": utc(), "parameters_unchanged": True, "generations_exact": True, "identity_controls_exact": all(c["exact"] for c in identity_controls), "identity_control_observations": identity_controls, "scope": ( "Fixed subset reload predictions exact; numerical inverse/restore " "outcomes recorded separately" ), "max_log_probability_error": max_logp_error, "evaluations": comparisons, "implementation_audit_sha256": file_hash(previous), "audit_source_sha256": file_hash(__file__), }, ) if (out / "interventions-complete.json").exists(): complete = json.loads((out / "interventions-complete.json").read_text()) complete["independently_reloaded"] = True complete["audit_finished_utc"] = utc() write_json(out / "complete.json", complete) write_json( out / "status.json", { "state": "complete", "independently_reloaded": True, "step": json.loads((out / "learning.json").read_text())[-1]["step"], }, ) print( json.dumps( { "run": out.name, "independent_reload": "passed", "evaluations": len(comparisons), "max_log_probability_error": max_logp_error, } ), flush=True, )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Controls separating knowledge load, derived supervision, and serial recall."""
from __future__ import annotations
import numpy as np
from .capacity_scaling import DIGIT, EOS, TYPE_B
def training_indices(world, spec, epoch): """Keep the historical mixed stream exactly, or replace derived examples.
Replay preserves the mixed stream's batch sizes/updates and each original atomic slot. Extra slots carry balanced atomic replay, never held-out labels. """ atoms = len(world["atomic"]) mixed = atoms + len(world["train_composition"]) mode = spec.get("training_mode", "mixed") if mode not in {"mixed", "atomic", "atomic_replay"}: raise ValueError(mode) n = atoms if mode == "atomic" else mixed rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) order = rng.permutation(n) if mode == "atomic_replay": replay_rng = np.random.default_rng( np.random.SeedSequence([spec["stream_seed"], epoch, 771]) ) replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) source = np.concatenate((np.arange(atoms), replacements)) return source[order] return order
def decode_bridge(predictions): """Reject malformed/out-of-domain predictions instead of oracle repairing.""" p = np.asarray(predictions) d = p[:, 1:5] - DIGIT valid = ( (p[:, 0] == TYPE_B) & (p[:, 5] == EOS) & ((d >= 0) & (d < 16)).all(1) & (d[:, :2] == 0).all(1) ) values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) return np.where(valid, values, 0), valid
def first_queries(compositions): rows = np.zeros_like(compositions) rows[:, 0] = 0 rows[:, 1:3] = compositions[:, 1:3] rows[:, 3] = -1 rows[:, 5:] = -1 return rows
def second_queries(compositions, bridges): rows = np.zeros_like(compositions) rows[:, 0] = 1 rows[:, 1] = bridges rows[:, 2] = compositions[:, 3] rows[:, 3] = -1 rows[:, 5:] = -1 return rows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""Fixed-vocabulary random worlds for the capacity development experiment.
Knowledge is in independent A->B and B->C maps. Composition labels are derived,never counted as independent information. This is a QA adaptation, not bioS."""
from __future__ import annotations
import hashlibimport math
import numpy as np
PAD, BOS, EOS, ANSWER = 0, 1, 2, 3TYPE_A, TYPE_B, TYPE_C = 4, 5, 6DIGIT, REL_A, REL_B = 7, 23, 27VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6
def digest_arrays(arrays): h = hashlib.sha256() for key, value in sorted(arrays.items()): value = np.ascontiguousarray(value) h.update(key.encode()) h.update(str(value.shape).encode()) h.update(str(value.dtype).encode()) h.update(value.tobytes()) return h.hexdigest()
def generate_world(spec): """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2.
The maximum address universe and all maps are generated before choosing a load. Prefix worlds are nested. Background controls keep the entire low-load composition training/evaluation sets, including necessary facts, unchanged. """ seed, heads = spec["world_seed"], spec["heads_n"] maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): raise ValueError("This version requires 256 values, four relations, <=65536 heads") support_heads = spec.get("support_heads_n", heads) if not 1 <= support_heads <= heads: raise ValueError("Invalid support prefix")
def rng(part): return np.random.default_rng(np.random.SeedSequence([seed, part]))
first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] second = rng(1).integers(values, size=(values, relations), dtype=np.int64) eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 eligible_second = rng(3).random((values, relations)) < 0.75 first_n = heads * relations h, r = np.indices(first.shape).reshape(2, -1) atoms_a = np.column_stack( ( np.zeros(first_n, dtype=int), h, r, -np.ones(first_n, dtype=int), first.ravel(), np.arange(first_n), -np.ones(first_n, dtype=int), ) ) b, r2 = np.indices(second.shape).reshape(2, -1) second_n = second.size atoms_b = np.column_stack( ( np.ones(second_n, dtype=int), b, r2, -np.ones(second_n, dtype=int), second.ravel(), first_n + np.arange(second_n), -np.ones(second_n, dtype=int), ) ) atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) bridge = first[h, r1] a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( np.int64 ) train_mask = ( eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) ) trained = np.zeros(len(atoms), dtype=bool) trained[comps[train_mask, 5:].ravel()] = True seen1, seen2 = trained[a_id], trained[b_id] world = { "first": first, "second": second, "atomic": atoms, "train_composition": comps[train_mask], } for name, mask in { "II": seen1 & seen2, "IO": seen1 & ~seen2, "OI": ~seen1 & seen2, "OO": ~seen1 & ~seen2, }.items(): ids = np.flatnonzero(mask & ~train_mask) # Selection stream does not depend on load in fixed-target controls. take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) world[name] = comps[take[: spec["evaluation_per_pool"]]] world[name + "_population"] = np.array([len(ids)], dtype=np.int64) panel_rng = rng(30) for name in ("atomic", "train_composition"): ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] world[name + "_panel"] = world[name][ids] world["role_counts"] = np.stack( [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] ) return world
def digits(values): values = np.asarray(values, dtype=np.int64) return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15)
def pack(rows): """Right padding is causally downstream; only answer+EOS is supervised.""" rows = np.asarray(rows, dtype=np.int64) x = np.zeros((len(rows), CONTEXT), dtype=np.int64) composition = rows[:, 0] == 2 prefix_length = np.where(composition, 9, 8) x[:, 0] = BOS x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) x[:, 2:6] = digits(rows[:, 1]) x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) x[composition, 8] = ANSWER labels = np.column_stack( (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) ) positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] return x, positions, labels
def information_ledger(world, parameters, knowledge_nll=None): facts = len(world["atomic"]) bits = facts * math.log2(world["second"].shape[0]) result = { "independent_facts": facts, "world_bits": bits, "parameters": parameters, "adjusted_parameters": parameters, "data_bits_per_parameter": bits / parameters, "composition_independent_bits": 0, } if knowledge_nll is not None: learned = bits - facts * knowledge_nll / math.log(2) result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) return result
def model_parameter_count(width, layers=2): # Tied token/output weights, learned positions, two biased projections each # in attention/MLP, per-block and final LayerNorms. return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width
def prerequisite_pass(metrics, thresholds): return all( metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") )
def grid_capacity(points, metric, threshold, atomic_threshold): """Report sampled successes and censoring, never silently assume monotonicity.""" points = sorted(points, key=lambda p: p["bits"]) passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] lower = max(successes) if successes else None failures_above = [ p["bits"] for p, ok in zip(points, passed, strict=True) if not ok and (lower is None or p["bits"] > lower) ] return { "largest_observed_passing_bits": lower, "next_observed_failing_bits": min(failures_above) if failures_above else None, "nonmonotonic_grid": reversals, "interpretation": "sampled_grid_only; bracket requires monotone interpolation", "censoring": "below_grid" if lower is None else ("above_grid" if not failures_above else "bracketed_on_grid"), }1234567891011121314151617181920212223242526272829303132"""Command-line interface for the deterministic matrix illustration."""
import argparseimport jsonfrom pathlib import Path
from .experiments import run_minimal_example
def main(argv: list[str] | None = None) -> int: """Print the analytical report as JSON and optionally save a copy.""" parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") parser.add_argument( "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" ) parser.add_argument( "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" ) parser.add_argument( "--output", type=Path, help="also save JSON to this path (creates parent directories)" ) args = parser.parse_args(argv) try: report = run_minimal_example(rank=args.rank, atol=args.atol) serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) if args.output is not None: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(serialized + "\n", encoding="utf-8") except (ValueError, OSError) as exc: parser.error(str(exc)) print(serialized) return 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477"""Distinct composition support and knowledge-load curves on random relation graphs.
The graph, answer/EOS objective, GPT blocks and optimizer reuse the previouslysuccessful Wang et al. adaptation. A fixed maximum entity vocabulary keepsparameters identical across loads. Development and confirmation worlds differ."""
from __future__ import annotations
import hashlibimport jsonimport mathimport osimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_model import ModelConfig, matmul_flopsfrom .grok_depth import ( EpochStream, GraphStep, SmallGPT, evaluate_rows, make_optimizer, pack_rows, two_calls, utc, write_json,)from .grok_depth_data import audit_world, build_world
def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def array_hash(arrays): digest = hashlib.sha256() for name, value in sorted(arrays.items()): digest.update(name.encode()) digest.update(np.asarray(value.shape, dtype="<i8").tobytes()) digest.update(value.astype("<i8", copy=False).tobytes()) return digest.hexdigest()
def prepare_world(spec): """Reserve once, permute once, take nested prefixes; never repeat support rows.""" n = spec["entities"] maximum = spec["max_entities"] if not 1 <= n <= maximum: raise ValueError("Entity count must fit the fixed vocabulary") base = build_world( spec["world_seed"], entities=n, relations=spec["relations"], degree=spec["degree"], phi=0, id_fraction=spec["id_fraction"], id_test_fraction=spec["test_fraction"], ) audit_world(base) rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960601])) order = rng.permutation(len(base["unused_composite"])) requested = round(spec["phi"] * len(base["id_atomic"])) if requested > len(order): raise ValueError("Distinct support request exceeds the reserved training pool") arrays = { key: base[key].copy() for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") } eligible = base["unused_composite"][order].copy() for rows in [*arrays.values(), eligible]: rows[:, 1:-1] += maximum - n identity = array_hash({**arrays, "eligible": eligible}) arrays["train_composite"] = eligible[:requested].copy() lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) atomic = arrays["atomic"] lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) first_counts = np.bincount(first, minlength=len(atomic)) second_counts = np.bincount(second, minlength=len(atomic)) role = {} for name in ("test_composite", "ood_composite"): one, two = constituent_indices(arrays[name], atomic, lookup, maximum) role[name] = { "n": len(one), "both_facts_seen_in_required_roles": ( float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) if len(one) else None ), } panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) panels = {} for key, name in [ ("atomic", "atomic"), ("id_atomic", "atomic_id"), ("ood_atomic", "atomic_ood"), ("test_composite", "II"), ("ood_composite", "OO"), ]: rows = arrays[key] ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) panels[name] = rows[ids].copy() panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() metadata = { "world_seed": spec["world_seed"], "entities": n, "max_entities": maximum, "relations": spec["relations"], "degree": spec["degree"], "vocab_size": maximum + spec["relations"] + 2, "atomic_examples": len(atomic), "id_atomic_examples": len(arrays["id_atomic"]), "composition_examples": requested, "eligible_compositions": len(eligible), "phi_actual": requested / len(arrays["id_atomic"]), "world_sha256": identity, "dataset_sha256": array_hash(arrays), "knowledge_bits": len(atomic) * math.log2(n), "entropy_condition": "independent uniform tails, conditional on head/relation keys", "composition_additional_independent_bits": 0, "role_coverage": role, "panel_counts": {key: len(value) for key, value in panels.items()}, "full_counts": {key: len(value) for key, value in arrays.items()}, "graph_source": base["metadata"]["source_url"], "graph_source_commit": base["metadata"]["source_commit"], "graph_audit": base["metadata"]["dataset_sha256"], } return arrays, panels, metadata
def constituent_indices(rows, atomic, lookup, maximum): first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] if np.any(first < 0): raise ValueError("Unknown first-hop fact") second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): raise ValueError("Composition truth differs from graph traversal") return first, second
def budget_nodes(spec, total): matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) compute = spec["compute_steps"] end = spec.get("fixed_steps", max(compute, matched)) nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) nodes.update(range(192000, end, 64000)) return sorted(nodes), {"compute": compute, "exposure": matched, "end": end}
def construct(spec, device): torch.manual_seed(spec["initialization"]) cfg = ModelConfig( vocab_size=spec["max_entities"] + spec["relations"] + 2, width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg
def model_hash(model): digest = hashlib.sha256() for name, tensor in model.state_dict().items(): digest.update(name.encode()) digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) return digest.hexdigest()
def measure(model, panels, device): metrics, predictions = {}, {} for name, rows in panels.items(): metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) if len(rows): metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) predictions.update({name + "_" + key: value for key, value in values.items()}) return metrics, predictions
def train(spec, out, resume=False): out = Path(out) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True device = torch.device("cuda:0") torch.cuda.set_device(device) arrays, panels, data = prepare_world(spec) model, cfg = construct(spec, device) lr = torch.tensor(spec["lr"], device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] table = tuple( torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) ) atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] total = atomic_n + composition_n stream = EpochStream(total, spec["stream_seed"]) nodes, budgets = budget_nodes(spec, total) start, seconds = 0, 0.0 counts = {"atomic": 0, "composition": 0} initial_hash = model_hash(model) if resume: saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: raise ValueError("Resume identity mismatch") model.load_state_dict(saved["model"]) optimizer.load_state_dict(saved["optimizer"]) lr = optimizer.param_groups[0]["lr"] for group in optimizer.param_groups: group["lr"] = lr stream.load_state_dict(saved["stream"]) counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] torch.set_rng_state(saved["cpu_rng"].cpu()) torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] out.mkdir(parents=True, exist_ok=True) metadata = { "spec": spec, "phase": spec["phase"], "pid": os.getpid(), "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), "gpu_name": torch.cuda.get_device_name(), "parameters": sum(p.numel() for p in model.parameters()), "initial_model_sha256": initial_hash, "world_sha256": data["world_sha256"], "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", "torch": torch.__version__, "numpy": np.__version__, "budgets": budgets, "evaluation_nodes": nodes, **data, } write_json(out / "run.json", metadata) write_json(out / "data-audit.json", data) np.savez_compressed(out / "world.npz", **arrays) np.savez_compressed(out / "panels.npz", **panels) t0 = time.perf_counter() graph = GraphStep(model, optimizer, table, spec["batch_size"]) capture = time.perf_counter() - t0 per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) history = json.loads((out / "learning.json").read_text()) if resume else [] history = [record for record in history if record["step"] <= start] begun = time.perf_counter()
def checkpoint(step, loss=None): metrics, predictions = measure(model, panels, device) record = { "step": step, "utc": utc(), "metrics": metrics, "training_seconds": seconds, "wall_seconds": time.perf_counter() - begun, "capture_seconds": capture, "examples": step * spec["batch_size"], "atomic_examples_seen": counts["atomic"], "composition_examples_seen": counts["composition"], "atomic_epochs": counts["atomic"] / atomic_n, "composition_epochs": counts["composition"] / composition_n if composition_n else 0, "minimum_record_exposures": (step * spec["batch_size"]) // total, "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), "supervised_tokens": step * spec["batch_size"] * 2, "executed_input_tokens": step * spec["batch_size"] * 4, "estimated_matmul_training_flops": step * per_step, "loss": loss, "learning_rate": float(lr.detach()), } history.append(record) write_json(out / "learning.json", history) payload = { "spec": spec, "world_sha256": data["world_sha256"], "step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "stream": stream.state_dict(), "counts": counts, "seconds": seconds, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(), } torch.save(payload, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(out / "latest.pt") if step in budgets.values(): torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"weights-{step}.pt", ) np.savez_compressed(out / f"predictions-{step}.npz", **predictions) status = { "state": "trained" if step == budgets["end"] else "running", "step": step, "budget": budgets["end"], "atomic": metrics["atomic"]["accuracy"], "II": metrics["II"]["accuracy"], "updated_utc": utc(), } write_json(out / "status.json", status) print(json.dumps(status), flush=True)
if not resume: checkpoint(0) for end in (node for node in nodes if node > start): torch.cuda.synchronize() t0 = time.perf_counter() loss = None step = start while step < end: length = min(256, end - step) indices = stream.take(length * spec["batch_size"]).reshape(length, -1) atom_count = int((indices < atomic_n).sum()) counts["atomic"] += atom_count counts["composition"] += indices.size - atom_count gpu_indices = torch.as_tensor(indices, device=device) for j in range(length): lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) loss = graph(gpu_indices[j]) step += length torch.cuda.synchronize() seconds += time.perf_counter() - t0 value = float(loss.detach()) if not math.isfinite(value): raise FloatingPointError(f"Nonfinite loss at {end}") checkpoint(end, value) start = end full_panels = { "atomic": arrays["atomic"], "atomic_id": arrays["id_atomic"], "atomic_ood": arrays["ood_atomic"], "II": arrays["test_composite"], "OO": arrays["ood_composite"], } full, predictions = measure(model, full_panels, device) full["external_two_calls"] = two_calls(model, panels["II"], device) np.savez_compressed(out / "full-predictions.npz", **predictions) write_json( out / "complete.json", { "step": start, "spec": spec, "parameters": metadata["parameters"], "training_seconds": seconds, "wall_seconds": time.perf_counter() - begun, "endpoint": history[-1], "full_metrics": full, "finished_utc": utc(), }, )
def audit(spec, out): """Reload both predeclared comparison checkpoints and independently recount.""" out = Path(out) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True arrays, panels, data = prepare_world(spec) recorded = dict(np.load(out / "world.npz")) if array_hash(recorded) != data["dataset_sha256"]: raise ValueError("Saved world differs from deterministic reconstruction") meta = json.loads((out / "run.json").read_text()) if meta["world_sha256"] != data["world_sha256"]: raise ValueError("World identity mismatch") history = json.loads((out / "learning.json").read_text()) nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) if [record["step"] for record in history] != nodes: raise ValueError("Missing or reordered evaluation nodes") model, cfg = construct(spec, "cuda:0") if sum(p.numel() for p in model.parameters()) != meta["parameters"]: raise ValueError("Parameter count mismatch") per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) for record in history: examples = record["step"] * spec["batch_size"] if record["examples"] != examples or examples != ( record["atomic_examples_seen"] + record["composition_examples_seen"] ): raise ValueError("Exposure arithmetic mismatch") if record["estimated_matmul_training_flops"] != record["step"] * per_step: raise ValueError("Executed-shape FLOP mismatch") reloaded = [] for step in sorted(set(budgets.values()) & set(nodes)): saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") if saved["spec"] != spec or saved["step"] != step: raise ValueError("Checkpoint identity mismatch") model.load_state_dict(saved["model"]) metrics, predictions = measure(model, panels, "cuda:0") original = dict(np.load(out / f"predictions-{step}.npz")) for key, values in predictions.items(): if key.endswith("_nll"): np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) elif not np.array_equal(values, original[key]): raise ValueError(f"Reloaded predictions changed: {step} {key}") prior = next(record for record in history if record["step"] == step)["metrics"] for name, metric in metrics.items(): if metric["accuracy"] != prior[name]["accuracy"]: raise ValueError("Metric recount mismatch") reloaded.append(step) full_panels = { "atomic": arrays["atomic"], "atomic_id": arrays["id_atomic"], "atomic_ood": arrays["ood_atomic"], "II": arrays["test_composite"], "OO": arrays["ood_composite"], } full, predictions = measure(model, full_panels, "cuda:0") original = dict(np.load(out / "full-predictions.npz")) for key, value in predictions.items(): np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") write_json( out / "audit.json", {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, ) write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()})
def calibrated_choice(records, thresholds): """Development-only success gate; prefer smaller registered model when both pass.""" candidates = [] for spec, metrics in records: passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) if passed: candidates.append(spec) return min(candidates, key=lambda spec: spec["layers"]) if candidates else None
def confirmation_specs(config, selected): specs = [] for index, seed in enumerate(config["confirmation_worlds"]): for phi in config["support_phi"]: specs.append( { **selected, "phase": "confirmation", "world_seed": seed, "initialization": config["initialization"] + index, "stream_seed": config["stream_seed"] + index, "name": f"support-w{index + 1}-phi{phi:g}", "phi": phi, "entities": config["base_spec"]["entities"], } ) return specs
def anchors_pass(records, worlds, thresholds): """Require exactly the registered independent worlds; no cherry-picked anchors.""" observed = [spec["world_seed"] for spec, _ in records] if len(observed) != len(worlds) or set(observed) != set(worlds): return False return all( all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) for _, metrics in records )
def load_specs(config, selected): specs = [] for index, seed in enumerate(config["confirmation_worlds"]): for n in config["load_entities"][1:]: specs.append( { **selected, "phase": "confirmation", "world_seed": seed, "initialization": config["initialization"] + index, "stream_seed": config["stream_seed"] + index, "name": f"load-w{index + 1}-n{n}", "phi": config["anchor_phi"], "entities": n, } ) return specs123456789101112131415161718192021222324252627282930313233343536"""Retry transient W&B connection failures without changing scientific trajectories."""
import jsonimport timeimport tracebackfrom datetime import datetime, timezonefrom pathlib import Path
from . import interface_trackingfrom .experiment_tracking import write_json
def utc(): return datetime.now(timezone.utc).isoformat()
def main(): import sys
root = Path(sys.argv[sys.argv.index("--root") + 1]) for attempt in range(1, 145): try: interface_tracking.main() return except Exception: path = root / "tracking-retries.json" history = json.loads(path.read_text()) if path.exists() else [] history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) write_json(path, history) print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) time.sleep(min(60, 5 * attempt)) raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669"""Ordinary end-to-end GPT depth and optimization-time development experiment.
The frozen random graph is shared across two-, three- and four-hop training.Only terminal entities enter composition text; intermediate truth is used forevaluation and audit. Existing experimental implementations remain unchanged."""
from __future__ import annotations
import hashlibimport jsonimport mathimport timefrom dataclasses import replacefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfigfrom .grok_depth import EpochStream, make_optimizer, utc, write_jsonfrom .grok_loop_data import build_world as single_length_worldfrom .grok_loop_model import LoopGPT, flopsfrom .latent_scaling import model_digestfrom .storage_composition import FullTokenStep, file_hashfrom .storage_frontier import learning_rate
BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3HOPS = (2, 3, 4)TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4")EVALUATION_SPLITS = ("atomic",) + tuple( f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict"))DATA_DEFAULTS = { "entities": 64, "relations": 4, "degree": 4, "phi": 4.0, "id_fraction": 0.75, "id_test_fraction": 0.2, "evaluation_size": 512,}SOURCE_FILES = [ "src/llm_memory_editability/bios_model.py", "src/llm_memory_editability/grok_depth.py", "src/llm_memory_editability/grok_depth_data.py", "src/llm_memory_editability/grok_loop_data.py", "src/llm_memory_editability/grok_multihop_data.py", "src/llm_memory_editability/grok_loop_model.py", "src/llm_memory_editability/latent_scaling.py", "src/llm_memory_editability/storage_composition.py", "src/llm_memory_editability/storage_frontier.py", "src/llm_memory_editability/text_pretrain.py", "src/llm_memory_editability/depth_step.py", "scripts/run_depth_step.py", "tests/test_depth_step.py",]
def data_digest(world): digest = hashlib.sha256() for name in EVALUATION_SPLITS: rows = world[name] digest.update(name.encode()) digest.update(np.asarray(rows.shape, dtype="<i8").tobytes()) digest.update(rows.astype("<i8", copy=False).tobytes()) meta = world["metadata"] digest.update( json.dumps( {key: meta[key] for key in ("world_seed", "entities", "relations", "id_mask")}, sort_keys=True, ).encode() ) return digest.hexdigest()
def truth_path_details(world, rows): """Return independent truth trajectories and constituent atomic row indices.""" rows = np.asarray(rows) atoms = world["atomic"] lookup = {(int(h), int(r)): (index, int(t)) for index, (h, r, t) in enumerate(atoms)} if len(lookup) != len(atoms): raise ValueError("Duplicate atomic keys") if rows.ndim != 2 or rows.shape[1] < 3: raise ValueError("Invalid compact truth rows") nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64) indices = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64) nodes[:, 0] = rows[:, 0] for i, row in enumerate(rows): current = int(row[0]) for j, relation in enumerate(row[1:-1]): edge = lookup.get((current, int(relation))) if edge is None: raise ValueError("Composition references a missing atomic edge") index, current = edge indices[i, j], nodes[i, j + 1] = index, current if current != int(row[-1]): raise ValueError("Composition terminal entity disagrees with graph truth") return nodes, indices
def audit_world(world): meta = world["metadata"] entities, relations = meta["entities"], meta["relations"] relation_offset = ENTITY_OFFSET + entities id_mask = np.asarray(meta["id_mask"], dtype=bool) if id_mask.shape != (len(world["atomic"]),): raise ValueError("Invalid atomic ID mask") counts = {} for name in EVALUATION_SPLITS: rows = world[name] expected_columns = 3 if name == "atomic" else int(name.rsplit("_", 1)[1]) + 2 if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != expected_columns: raise ValueError("Invalid compact array shape/dtype: " + name) if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= relation_offset)): raise ValueError("Invalid entity token: " + name) if np.any( (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) ): raise ValueError("Invalid relation token: " + name) if len(set(map(tuple, rows[:, :-1]))) != len(rows): raise ValueError("Duplicate complete query: " + name) _, edges = truth_path_details(world, rows) if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): raise ValueError("Non-ID fact in familiar training/test: " + name) if name.startswith("strict_") and id_mask[edges].any(): raise ValueError("ID fact in strict composition: " + name) counts[name] = len(rows) if len(world["atomic"]) != entities * meta["degree"]: raise ValueError("Atomic graph degree does not match the contract") for hop in HOPS: query_sets = [ set(map(tuple, world[f"{split}_{hop}"][:, :-1])) for split in ("train", "familiar", "strict") ] if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): raise ValueError("Complete query leakage between length-specific splits") trained_edges = set() for hop in HOPS: trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) for hop in HOPS: strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) if strict_edges & trained_edges: raise ValueError("Strict facts participated in another length's composition training") digest = data_digest(world) if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: raise ValueError("Frozen dataset digest differs from actual arrays") return { "passed": True, "counts": counts, "dataset_sha256": digest, "truth_edges_independently_traversed": True, "complete_query_overlap": 0, "all_strict_facts_absent_from_composition_training": True, "cross_length_subpath_holdout": False, }
def build_world(spec): seed = spec.get("world_seed", spec.get("world")) if seed is None: raise ValueError("A fixed world_seed is required") settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} world, shared_atoms, shared_ids = {}, None, None source_metadata = {} for hop in HOPS: original = single_length_world({"world_seed": seed, "hops": hop, **settings}) # The historical graph reserves only PAD/EOS and uses entity offset 2. # Shift every entity/relation token once to reserve the explicit BOS=2. atoms = original["atomic"] + 1 id_set = set(map(tuple, original["id_atomic"])) id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) if shared_atoms is None: shared_atoms, shared_ids = atoms.copy(), id_mask.copy() elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): raise ValueError("Path lengths do not share identical graph and ID mask") world[f"train_{hop}"] = original["train_composite"] + 1 world[f"familiar_{hop}"] = original["test_full_composite"] + 1 world[f"strict_{hop}"] = original["ood_composite"] + 1 source_metadata[str(hop)] = original["metadata"] world["atomic"] = shared_atoms world["metadata"] = { "world_seed": int(seed), **settings, "id_mask": shared_ids.tolist(), "source_worlds": source_metadata, "same_atomic_and_id_mask_all_lengths": True, "source_entity_offset": 2, "entity_offset": ENTITY_OFFSET, "source_token_shift": 1, "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, "evaluation_pools": "Complete test_full_composite and ood_composite", "composition_supervision": "Terminal entity only; no intermediate entity", "training_objective": "All nonpadding next tokens including EOS", "holdout": "Complete queries held out within each length; not subpaths across lengths", } report = audit_world(world) world["metadata"]["dataset_sha256"] = report["dataset_sha256"] world["metadata"]["independent_audit"] = report expected = spec.get("frozen_data_sha256") if expected is not None and expected != report["dataset_sha256"]: raise ValueError("Rebuilt data differ from the frozen specification") return world
def construct(spec, device): if spec.get("context", 9) < 9: raise ValueError("Context must support four-hop answer and EOS") config = ModelConfig( vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=spec.get("context", 9), ) if config.layers > 6: raise ValueError("Canonical paired initialization is limited to six unique blocks") torch.manual_seed(spec["initialization"]) canonical = LoopGPT( replace(config, layers=6), repeats=1, dropout=spec.get("dropout", 0.0), initialization="scaled_effective", ) model = LoopGPT( config, repeats=spec["repeats"], dropout=spec.get("dropout", 0.0), initialization="scaled_effective", ) initial = canonical.state_dict() state = {} factor = math.sqrt(6 / (config.layers * spec["repeats"])) for key in model.state_dict(): value = initial[key].clone() if key.endswith(("attention.proj.weight", "mlp.down.weight")): value.mul_(factor) state[key] = value model.load_state_dict(state) return model.to(device)
def prompt_rows(rows, separator=71): rows = np.asarray(rows, dtype=np.int64) return np.c_[ np.full(len(rows), BOS, dtype=np.int64), rows[:, :-1], np.full(len(rows), separator, dtype=np.int64), ]
def pack_rows(rows, sequence=8, separator=71): """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" rows = np.asarray(rows, dtype=np.int64) sentence = np.c_[ prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) ] length = sentence.shape[1] - 1 if length > sequence: raise ValueError("Packed sequence is too short") tokens = np.zeros((len(rows), sequence), dtype=np.int64) labels = np.full_like(tokens, -100) tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] return tokens, labels
def run_name(spec): seed = spec.get("world_seed", spec.get("world")) return ( f"w{seed}-i{spec['initialization']}-d{spec['width']}" f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" )
def _mean(values): return float(np.asarray(values).mean()) if len(values) else None
@torch.no_grad()def generate_rows(model, rows, device, separator=71, batch_size=512): """Ordinary full forward, then free tail/EOS generation with answer feedback.""" rows = np.asarray(rows, dtype=np.int64) generated, nll = [], [] for start in range(0, len(rows), batch_size): batch = rows[start : start + batch_size] tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) first = model(tokens)[:, -1] target = torch.as_tensor(batch[:, -1], device=device) nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) answer = first.argmax(-1) tokens = torch.cat([tokens, answer[:, None]], dim=1) stop = model(tokens)[:, -1].argmax(-1) generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) answer_correct = pred[:, 0] == rows[:, -1] correct = answer_correct & (pred[:, 1] == EOS) return { "n": len(rows), "accuracy": _mean(correct), "answer_accuracy": _mean(answer_correct), "answer_nll": _mean(nll), }, {"generated": pred, "correct": correct, "answer_nll": nll}
@torch.no_grad()def evaluate(model, world, device): before = model.training model.eval() metrics, predictions = {}, {} separator = world["metadata"]["separator_token"] try: atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) metrics["atomic"] = atomic_metrics predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) for name in EVALUATION_SPLITS[1:]: rows = world[name] task_metrics, direct = generate_rows(model, rows, device, separator) nodes, edges = truth_path_details(world, rows) coverage = atomic_pred["correct"][edges].all(axis=1) current = rows[:, 0].copy() hops = rows.shape[1] - 2 calls = np.empty((len(rows), hops, 2), dtype=np.int64) for hop in range(hops): query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] _, result = generate_rows(model, query, device, separator) calls[:, hop] = result["generated"] current = result["generated"][:, 0] formats = (calls[:, :, 1] == EOS).all(axis=1) autonomous_correct = formats & (current == rows[:, -1]) path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) task_metrics.update( { "atomic_correct_coverage": _mean(coverage), "conditional_accuracy": _mean(direct["correct"][coverage]), "autonomous_two_calls": _mean(autonomous_correct), "autonomous_path_accuracy": _mean(path_correct), "hop_count": hops, } ) metrics[name] = task_metrics direct.update( { "coverage": coverage, "autonomous_generated": calls, "autonomous_correct": autonomous_correct, "autonomous_path_correct": path_correct, } ) predictions.update({name + "_" + key: value for key, value in direct.items()}) finally: model.train(before) return metrics, predictions
def _validate_spec(spec): nodes = spec["nodes"] if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: raise ValueError("Nodes must increase from initialization to the fixed endpoint") if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( spec["checkpoint_nodes"] ): raise ValueError("Checkpoint nodes must include initialization and endpoint") if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: raise ValueError("The fixed design requires four 32-example streams and dropout zero") if spec.get("model_initialization", "scaled_effective") != "scaled_effective": raise ValueError("The batch uses scaled_effective residual initialization")
def _save_world(out, world): np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) write_json(out / "world-metadata.json", world["metadata"])
def _check_source(source): if not source or any(file_hash(path) != digest for path, digest in source.items()): raise RuntimeError("Actual source differs from the required frozen source hashes")
def _validate_output(out): """Permit scheduler control files while preserving every existing experiment artifact.""" out = Path(out) if out.exists(): for path in out.iterdir(): allowed = path.is_file() and ( path.name == "input-spec.json" or path.name.endswith("-process.log") ) if not allowed: raise FileExistsError( "Do not overwrite an existing experiment artifact: " + str(path) )
def train(spec, out, source, device="cuda:0"): _validate_spec(spec) _check_source(source) if "frozen_data_sha256" not in spec: raise ValueError("Training requires frozen_data_sha256") out = Path(out) _validate_output(out) out.mkdir(parents=True, exist_ok=True) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.cuda.set_device(torch.device(device)) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True started_process = time.perf_counter() world = build_world(spec) digest = data_digest(world) _save_world(out, world) write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) model = construct(spec, device) initial_digest = model_digest(model) lr = torch.tensor(spec["lr"], device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) strata = [world[name] for name in TRAIN_SPLITS] sizes = [len(rows) for rows in strata] if any(size == 0 for size in sizes): raise ValueError("Do not reroll a world with an empty sampled training stratum") packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] table = tuple( torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) ) offsets = np.cumsum([0, *sizes[:-1]]) streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] counts = [np.zeros(size, dtype=np.int64) for size in sizes] graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) history, step, training_seconds = [], 0, 0.0
def measure(loss=None): metrics, predictions = evaluate(model, world, device) row = { "step": step, "lr": learning_rate(spec, step) if step else 0.0, "metrics": metrics, "loss": loss, "training_seconds": training_seconds, "estimated_training_flops": step * flop_step, "supervised_tokens": step * token_step, "padded_input_tokens": step * spec["batch_size"] * 8, } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) np.savez_compressed( out / f"exposures-{step:06d}.npz", **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, ) state = { "spec": spec, "step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "streams": [s.state_dict() for s in streams], "counts": counts, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), "source": source, "data_sha256": digest, } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(out / "latest.pt") if step in spec["checkpoint_nodes"]: torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"model-{step:06d}.pt", ) write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) print( json.dumps( { "run": run_name(spec), "step": step, "atomic": metrics["atomic"]["accuracy"], "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, } ), flush=True, ) return row
measure() for end in spec["nodes"][1:]: torch.cuda.synchronize() started = time.perf_counter() while step < end: updates = min(128, end - step) indices = [] for i, stream in enumerate(streams): draws = stream.take(updates * 32).reshape(updates, 32) counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) indices.append(draws + offsets[i]) indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) for j in range(updates): lr.fill_(learning_rate(spec, step + j + 1)) loss = graph(indices[j]) step += updates torch.cuda.synchronize() training_seconds += time.perf_counter() - started loss_value = float(loss) if not np.isfinite(loss_value): raise FloatingPointError("Nonfinite loss at step " + str(step)) endpoint = measure(loss_value) np.savez_compressed( out / "exposures.npz", **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, ) result = { "spec": spec, "source": source, "data_sha256": digest, "initial_model_sha256": initial_digest, "checkpoint_sha256": file_hash(out / "latest.pt"), "finished_utc": utc(), "parameters": sum(p.numel() for p in model.parameters()), "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), "endpoint": endpoint, "supervised_tokens": step * token_step, "padded_input_tokens": step * spec["batch_size"] * 8, "estimated_training_flops": step * flop_step, "training_seconds": training_seconds, "process_seconds": time.perf_counter() - started_process, "environment": { "torch": torch.__version__, "numpy": np.__version__, "cuda": torch.version.cuda, "gpu": torch.cuda.get_device_name(device), "tf32": True, }, } write_json(out / "complete.json", result) return result
def compare_metrics(actual, expected): if set(actual) != set(expected): raise AssertionError("Metric task keys differ") for task, values in actual.items(): if set(values) != set(expected[task]): raise AssertionError("Metric field keys differ") for key, value in values.items(): if key == "answer_nll" and value is not None: np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) elif value != expected[task][key]: raise AssertionError(f"Saved metric differs: {task}.{key}")
def compare_predictions(actual, path): maximum = 0.0 with np.load(path) as saved: if set(actual) != set(saved.files): raise AssertionError("Prediction keys differ") for key, value in actual.items(): if key.endswith("answer_nll"): np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) if value.size: maximum = max(maximum, float(np.abs(value - saved[key]).max())) else: np.testing.assert_array_equal(value, saved[key]) return maximum
def audit(out, device="cuda:0"): out = Path(out) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.cuda.set_device(torch.device(device)) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True result = json.loads((out / "complete.json").read_text()) recorded = json.loads((out / "spec.json").read_text()) source, spec = result["source"], result["spec"] _check_source(source) _validate_spec(spec) if recorded["spec"] != spec or recorded["source"] != source: raise AssertionError("Recorded specification/source differ") if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: raise AssertionError("Latest checkpoint hash differs") world = build_world(spec) digest = data_digest(world) if digest != result["data_sha256"] or digest != recorded["data_sha256"]: raise AssertionError("Rebuilt data differ from records") if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: raise AssertionError("Archived world metadata differ") with np.load(out / "world.npz") as archived: if set(archived.files) != set(EVALUATION_SPLITS): raise AssertionError("Archived world keys differ") for name in EVALUATION_SPLITS: np.testing.assert_array_equal(archived[name], world[name]) model = construct(spec, device) if model_digest(model) != result["initial_model_sha256"]: raise AssertionError("Paired initialization differs") history = json.loads((out / "learning.json").read_text()) if [row["step"] for row in history] != spec["nodes"]: raise AssertionError("Recorded learning nodes differ") by_node = {row["step"]: row for row in history} if by_node[spec["steps"]] != result["endpoint"]: raise AssertionError("Endpoint differs from the learning curve") maximum = 0.0 for node in spec["checkpoint_nodes"]: checkpoint = torch.load( out / f"model-{node:06d}.pt", map_location=device, weights_only=False ) if checkpoint["spec"] != spec or checkpoint["step"] != node: raise AssertionError("Checkpoint specification/node differ") model.load_state_dict(checkpoint["model"]) metrics, predictions = evaluate(model, world, device) compare_metrics(metrics, by_node[node]["metrics"]) maximum = max( maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") ) saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) if ( saved["spec"] != spec or saved["source"] != source or saved["step"] != spec["steps"] or saved["data_sha256"] != digest ): raise AssertionError("Latest state identity differs") sizes = [len(world[name]) for name in TRAIN_SPLITS] streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] counts = [np.zeros(size, dtype=np.int64) for size in sizes] previous = 0 for node in spec["nodes"]: for i, stream in enumerate(streams): draws = ( stream.take((node - previous) * 32) if node > previous else np.empty(0, dtype=np.int64) ) counts[i] += np.bincount(draws, minlength=sizes[i]) with np.load(out / f"exposures-{node:06d}.npz") as actual: for name, count in zip(TRAIN_SPLITS, counts, strict=True): np.testing.assert_array_equal(actual[name], count) previous = node with np.load(out / "exposures.npz") as actual: for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): np.testing.assert_array_equal(actual[name], count) np.testing.assert_array_equal(saved["counts"][i], count) if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: raise AssertionError("EpochStream actual exposures are unbalanced") stream = EpochStream(sizes[i], spec["stream_seed"] + i) stream.load_state_dict(saved["streams"][i]) np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) model.load_state_dict(saved["model"]) metrics, predictions = evaluate(model, world, device) compare_metrics(metrics, result["endpoint"]["metrics"]) maximum = max( maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") ) checked = { "passed": True, "dataset_rebuilt_and_archived_exact": True, "initial_model_exact": True, "checkpoint_nodes": spec["checkpoint_nodes"], "endpoint_tokens_exact": True, "all_nodes_exposure_counters_exact": True, "stream_state_continuation_exact": True, "max_nll_difference": maximum, "nll_rtol": 1e-5, "nll_atol": 1e-5, "utc": utc(), } write_json(out / "audit.json", checked) return checked123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371"""Answer-only MLP editing calibration with frozen parent-logit regularization.
This development grid changes the editor objective and learning rate, preservingthe completed v1 experiment. KL on a finite replay set is a regularizer, not anexact preservation constraint. Kdev checks the operation; U never selects it."""
from __future__ import annotations
import copyimport hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .depth_step import EOS, pack_rowsfrom .depth_step import SOURCE_FILES as TRAIN_SOURCESfrom .depth_step_mechanism import edit_cases, generatefrom .grok_depth import utc, write_jsonfrom .latent_scaling import model_digestfrom .storage_composition import file_hash
SOURCE_FILES = list( dict.fromkeys( [ *TRAIN_SOURCES, "src/llm_memory_editability/depth_step_mechanism.py", "src/llm_memory_editability/depth_step_edit_calibration.py", "scripts/calibrate_depth_step_edit.py", "tests/test_depth_step_edit_calibration.py", ] ))PARAMETER = "blocks.0.mlp.down.weight"NODES = (0, 20, 100, 200)LEARNING_RATES = (0.0001, 0.001, 0.003)
def _array_hash(array): array = np.asarray(array) digest = hashlib.sha256(str(array.dtype).encode()) digest.update(np.asarray(array.shape, dtype="<i8").tobytes()) digest.update(array.tobytes()) return digest.hexdigest()
def calibration_cases(world, n_cases=2, replay_n=32, keep_n=32, total_cases=8): """Partition fixed cases without consulting a checkpoint or any predictions.""" all_cases = edit_cases(world, n_facts=total_cases, replay_n=replay_n) if not 0 < n_cases <= total_cases: raise ValueError("Invalid calibration-case prefix") atoms = world["atomic"] order = sorted(range(len(atoms)), key=lambda index: tuple(atoms[index])) for case in all_cases[:n_cases]: successor_rows = set(map(tuple, case["tasks"]["necessary_successor_atomic"])) successor_indices = {i for i, row in enumerate(atoms) if tuple(row) in successor_rows} excluded = {case["atomic_index"], *case["replay_indices"], *successor_indices} keep_indices = [i for i in order if i not in excluded][:keep_n] if len(keep_indices) != keep_n: raise ValueError("Insufficient development keep atoms") case["keep_dev_indices"] = keep_indices case["tasks"]["Kdev_atomic"] = atoms[keep_indices].copy() excluded_u = {case["atomic_index"], *case["replay_indices"], *keep_indices} unused = [i for i in range(len(atoms)) if i not in excluded_u] case["unused_atomic_indices"] = unused case["tasks"]["U_atomic"] = atoms[unused].copy() return all_cases[:n_cases], [case["atomic_index"] for case in all_cases[n_cases:]]
def answer_eos_batch(rows, world, device): """Select only SEP->answer and teacher-forced answer->EOS supervision.""" rows = np.asarray(rows, dtype=np.int64) tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) batch_indices = np.arange(len(rows))[:, None] selected = labels[batch_indices, positions] if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): raise ValueError("Answer/EOS positions disagree with the packed sequence") return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected))
def answer_eos_logits(model, batch): tokens, positions, _labels = batch return model(tokens, positions=positions)
def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" if parent_log_probabilities.requires_grad: raise ValueError("Parent logits must be detached") target_logits = answer_eos_logits(model, target_batch) ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) kl = F.kl_div( replay_log.flatten(0, 1), parent_log_probabilities.flatten(0, 1), reduction="batchmean", log_target=True, ) return ce + kl, ce, kl
def _measure(model, case, world, device, step): metrics, raw = {}, {} for name, rows in case["tasks"].items(): values, predictions = generate(model, rows, world, device) if name in case["original_d_rows"]: original = case["original_d_rows"][name] changed = rows[:, -1] != original[:, -1] predicted = predictions["predictions"] correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) values.update( { "changed_answer_n": int(changed.sum()), "changed_answer_coverage": float(changed.mean()) if len(rows) else None, "changed_answer_accuracy": float(correct[changed].mean()) if changed.any() else None, "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, } ) metrics[name] = values raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) return metrics, raw
def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): """One independently initialized branch, with fixed parent KL reference.""" if arm not in {"edit", "review"}: raise ValueError("Arm must be edit or review") if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: raise ValueError("Nodes must increase from zero") parent_hash = model_digest(model) edited = copy.deepcopy(model).eval() for name, parameter in edited.named_parameters(): parameter.requires_grad_(name == PARAMETER) parameter.grad = None before = {name: value.detach().clone() for name, value in edited.state_dict().items()} parameter = dict(edited.named_parameters())[PARAMETER] optimizer = torch.optim.Adam([parameter], lr=lr) target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) target_batch = answer_eos_batch(target_rows, world, device) replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) with torch.no_grad(): parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() raw = { "parent_replay_log_probabilities": parent_log.cpu().numpy(), "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), } for name, old_rows in case["original_d_rows"].items(): raw[name + "_original_rows"] = old_rows raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] step, history, loss_values = 0, [], None for node in nodes: while step < node: optimizer.zero_grad(set_to_none=True) loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) loss.backward() optimizer.step() step += 1 loss_values = { "total": float(loss.detach()), "target_ce": float(ce.detach()), "replay_kl": float(kl.detach()), } metrics, predictions = _measure(edited, case, world, device, step) raw.update(predictions) target_name = "E_new" if arm == "edit" else "E_old" keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 target_pass = metrics[target_name]["accuracy"] == 1.0 history.append( { "step": step, "loss": loss_values, "metrics": metrics, "Kdev_at_least_95_percent": keep_pass, "target_atomic_success": target_pass, "calibration_operation_pass": keep_pass and target_pass, } ) changed = [ name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) ] if set(changed) - {PARAMETER}: raise ValueError("A frozen state tensor changed") if model_digest(model) != parent_hash: raise ValueError("Original checkpoint model changed") delta = parameter.detach() - before[PARAMETER] raw["mlp_down_weight_delta"] = delta.cpu().numpy() record = { "arm": arm, "lr": lr, "atomic_index": case["atomic_index"], "old_fact": case["old_fact"], "new_fact": case["new_fact"], "replay_indices": case["replay_indices"], "keep_dev_indices": case["keep_dev_indices"], "unused_atomic_indices": case["unused_atomic_indices"], "parent_model_sha256": parent_hash, "final_model_sha256": model_digest(edited), "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), "updated_parameter": PARAMETER, "changed_state_tensors": changed, "weight_delta_l2": float(delta.norm()), "history": history, } return record, raw
def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): """Freeze data, all arms, sources, and initial weights before any model inference.""" out = Path(out) out.mkdir(parents=True, exist_ok=False) if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): raise ValueError("Invalid learning rate") cases, remaining = calibration_cases(world, n_cases=n_cases) serialized = [] for case in cases: entry = { key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} } entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} entry["original_d_rows"] = { key: value.tolist() for key, value in case["original_d_rows"].items() } serialized.append(entry) config = { "phase": "development_calibration", "created_utc": utc(), "source_checkpoint": source, "source": {path: file_hash(path) for path in SOURCE_FILES}, "parent_model_sha256": model_digest(model), "initial_down_weight_sha256": _array_hash( model.blocks[0].mlp.down.weight.detach().cpu().numpy() ), "learning_rates": list(learning_rates), "nodes": list(NODES), "cases": serialized, "n_cases": n_cases, "matrix": [ {"case": i, "lr": lr, "arm": arm} for i in range(n_cases) for lr in learning_rates for arm in ("edit", "review") ], "reserved_original_case_indices": remaining, "reserved_cases_are_independent_world_confirmation": False, "optimizer": "Adam, no weight decay", "parameter": PARAMETER, "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", "replay_kl_weight": 1.0, "supervised_prefix_tokens": 0, "trained_compositions": 0, "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", "Kdev_threshold": 0.95, "U_selection": "All remaining atomic facts, including unused necessary successors", "U_or_D_select_editor": False, "all_grid_failures_retained": True, "executions_affected_by_shared_edit": model.repeats, "limits": [ "Finite replay KL is not strict output preservation", "A successful Kdev check does not establish unobserved U preservation", "Cases share one development world and original checkpoints", ], } write_json(out / "calibration-config.json", config) return config, cases
def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): """Validate an existing prepared configuration, without rewriting it.""" out = Path(out) config_file = out / "calibration-config.json" config = json.loads(config_file.read_text()) if any(path.name != config_file.name for path in out.iterdir()): raise FileExistsError("Existing branch artifacts prevent a repeated execution") if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: raise ValueError("Requested grid differs from prepared calibration") expected_source = config["source_checkpoint"] for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): if source[key] != expected_source[key]: raise ValueError("Checkpoint or data differ from prepared calibration: " + key) if model_digest(model) != config["parent_model_sha256"]: raise ValueError("Parent parameter hash differs from prepared calibration") expected_matrix = [ {"case": i, "lr": lr, "arm": arm} for i in range(n_cases) for lr in learning_rates for arm in ("edit", "review") ] if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): raise ValueError("Prepared update matrix or nodes changed") if ( config["parameter"] != PARAMETER or config["replay_kl_weight"] != 1.0 or config["Kdev_threshold"] != 0.95 or config["U_or_D_select_editor"] ): raise ValueError("Prepared operation contract changed") cases, remaining = calibration_cases(world, n_cases=n_cases) if remaining != config["reserved_original_case_indices"]: raise ValueError("Reserved cases changed") for case, frozen in zip(cases, config["cases"], strict=True): for key in ( "atomic_index", "old_fact", "new_fact", "replay_indices", "keep_dev_indices", "unused_atomic_indices", "propagation_scope", ): if case[key] != frozen[key]: raise ValueError("Case selection changed: " + key) if set(case["tasks"]) != set(frozen["task_rows"]): raise ValueError("Prepared task set changed") for name, rows in case["tasks"].items(): if ( rows.tolist() != frozen["task_rows"][name] or _array_hash(rows) != frozen["task_sha256"][name] ): raise ValueError("Prepared task rows changed: " + name) for name, rows in case["original_d_rows"].items(): if rows.tolist() != frozen["original_d_rows"][name]: raise ValueError("Prepared original D labels changed") for path, expected in config["source"].items(): if file_hash(path) != expected: raise ValueError("Source changed after calibration freeze: " + path) return config, cases
def execute_calibration(model, world, config, cases, out, device): out = Path(out) if model_digest(model) != config["parent_model_sha256"]: raise ValueError("Parent parameter hash differs from frozen configuration") for path, expected in config["source"].items(): if file_hash(path) != expected: raise ValueError("Source changed after calibration freeze: " + path) for case, expected in zip(cases, config["cases"], strict=True): for name, rows in case["tasks"].items(): if _array_hash(rows) != expected["task_sha256"][name]: raise ValueError("Task rows changed after freeze: " + name) started = time.perf_counter() records = [] for item in config["matrix"]: number, lr, arm = item["case"], item["lr"], item["arm"] record, raw = calibrated_edit_one( model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) ) label = f"case{number:02d}-lr{lr:.4f}-{arm}" np.savez_compressed(out / (label + "-raw.npz"), **raw) write_json(out / (label + ".json"), record) records.append(record) print(f"Calibration branch completed: {label}", flush=True) report = { "phase": "development_calibration", "records": records, "config_sha256": file_hash(out / "calibration-config.json"), "completed_branches": len(records), "wall_seconds": time.perf_counter() - started, "model_selection_by_U_or_D": False, } write_json(out / "calibration-summary.json", report) return report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589"""Descriptive entity readouts, pure-first-hop interventions and MLP edits.
No fitted probe or performance predictor is used. Residual readouts and raw MLPcosines are descriptions; only interventions test a causal contribution. Thetruth graph chooses queries, donors and edits before any model is evaluated."""
from __future__ import annotations
import copyimport jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_detailsfrom .grok_depth import utc, write_jsonfrom .storage_composition import file_hash
def traced_forward(model, tokens, patches=None): """Use the real SDPA computation and record every executed block/position.
Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) to a batch of replacement vectors. Repeated executions of a shared block remain separately indexed. Attention maps are descriptive manual softmax; the forward uses the same SDPA primitive as LoopGPT. """ if model.training: raise ValueError("Tracing requires evaluation mode") patches = patches or {} length = tokens.shape[1] x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} consumed = set() for index, block in enumerate(model.iter_blocks()): z = block.ln1(x) batch, _, width = z.shape a = block.attention q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) q, k, v = (part.transpose(1, 2) for part in (q, k, v)) scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + attention_delta mlp_delta = block.mlp(block.ln2(x)) for key, replacement in patches.items(): layer, component, position = key if layer == index and component == "mlp_delta": if replacement.shape != mlp_delta[:, position].shape: raise ValueError("Patch shape differs from selected MLP position") mlp_delta = mlp_delta.clone() mlp_delta[:, position] = replacement consumed.add(key) x = x + mlp_delta for key, replacement in patches.items(): layer, component, position = key if layer == index and component == "postresidual": if replacement.shape != x[:, position].shape: raise ValueError("Patch shape differs from selected residual position") x = x.clone() x[:, position] = replacement consumed.add(key) for key, value in ( ("attention_map", attention_map), ("attention_delta", attention_delta), ("mlp_delta", mlp_delta), ("postresidual", x), ): cache[key].append(value.detach()) if consumed != set(patches): raise ValueError("Unknown execution/component in patch") logits = F.linear(model.ln_final(x), model.token.weight) return logits, {key: torch.stack(values) for key, values in cache.items()}
def _separator(world): return int(world["metadata"]["separator_token"])
def _mean(values): return float(np.mean(values)) if len(values) else None
@torch.no_grad()def generate(model, rows, world, device, batch_size=256): """Free answer then free EOS, retaining full-vocabulary probabilities.""" rows = np.asarray(rows, dtype=np.int64) predictions, probabilities, gold_probabilities = [], [], [] for begin in range(0, len(rows), batch_size): selected = rows[begin : begin + batch_size] tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) probability = model(tokens)[:, -1].softmax(-1) answer = probability.argmax(-1) eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) probabilities.append(probability.cpu().numpy()) gold_probabilities.append( probability[ torch.arange(len(selected), device=device), torch.as_tensor(selected[:, -1], device=device), ] .cpu() .numpy() ) vocab = model.config.vocab_size predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) prob = ( np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) ) gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) correct = predicted[:, 0] == rows[:, -1] return { "n": len(rows), "answer_accuracy": _mean(correct), "accuracy": _mean(correct & (predicted[:, 1] == EOS)), "gold_probability": _mean(gold_prob), }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob}
def select_donors(world, rows): """Lexicographic donors know exactly one fact and no target second relation.""" atoms = world["atomic"] lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) nodes, _ = truth_path_details(world, rows) same, changed, changed_tail = [], [], [] for row, path in zip(rows, nodes, strict=True): h, r1, r2, old_tail = map(int, row) bridge = int(path[1]) identical = next( (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 ) different = next( ( i for i in order if int(atoms[i, 2]) != bridge and (int(atoms[i, 2]), r2) in lookup and lookup[(int(atoms[i, 2]), r2)] != old_tail ), -1, ) same.append(identical) changed.append(different) changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) return { "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), }
@torch.no_grad()def entity_readouts(model, cache, targets, entities): """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" residual = cache["postresidual"] logits = F.linear(model.ln_final(residual), model.token.weight) entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] probabilities = logits.softmax(-1) entity_probabilities = entity_logits.softmax(-1) embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T arrays = {} for name, token_ids in targets.items(): ids = torch.as_tensor(token_ids, device=residual.device) full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) entity_ids = full_ids - ENTITY_OFFSET gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( -1 ) arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( -1, entity_ids ).squeeze(-1) arrays[name + "_mlp_embedding_cosine"] = gold_cosine arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) return {name: value.cpu().numpy() for name, value in arrays.items()}
@torch.no_grad()def _patched_generation(model, tokens, patch): logits, _ = traced_forward(model, tokens, patch) probability = logits[:, -1].softmax(-1) answer = probability.argmax(-1) # Reapply the same intervention while freely generating the EOS token. extended = torch.cat((tokens, answer[:, None]), dim=1) eos_logits, _ = traced_forward(model, extended, patch) eos = eos_logits[:, -1].argmax(-1) return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy()
def trace_analysis(model, world, out, device, max_queries=128): out = Path(out) out.mkdir(parents=True, exist_ok=False) model.eval() started = time.perf_counter() raw, baseline = {}, {} for split in ("atomic", "familiar_2", "strict_2"): metrics, prediction = generate(model, world[split], world, device) baseline[split] = metrics raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) indices = np.arange(min(max_queries, len(world["familiar_2"]))) rows = world["familiar_2"][indices] nodes, edges = truth_path_details(world, rows) tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) with torch.no_grad(): reference = model(tokens) actual, cache = traced_forward(model, tokens) difference = float((actual - reference).abs().max()) torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) if not torch.equal(actual.argmax(-1), reference.argmax(-1)): raise ValueError("Traced forward changes full-vocabulary argmax") raw.update( { "query_indices": indices, "query_rows": rows, "truth_nodes": nodes, "truth_atomic_indices": edges, } ) raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) raw.update( entity_readouts( model, cache, {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, world["metadata"]["entities"], ) ) donors = select_donors(world, rows) raw.update(donors) atom_predictions = raw["baseline_atomic_predictions"] atoms = world["atomic"] atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) records = [] for style in ("self", "same_bridge", "different_bridge"): donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] valid = donor_ids >= 0 selected = np.flatnonzero(valid) if not len(selected): continue donor_rows = world["atomic"][donor_ids[valid]] donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) with torch.no_grad(): _, donor_cache = traced_forward(model, donor_tokens) expected = ( donors["different_bridge_tail"][valid] if style == "different_bridge" else rows[valid, -1] ) new_second_indices = np.asarray( [ atomic_key_indices[(int(donor[2]), int(query[2]))] for donor, query in zip(donor_rows, rows[valid], strict=True) ] ) premises = ( atom_correct[edges[valid]].all(1) & atom_correct[donor_ids[valid]] & atom_correct[new_second_indices] ) raw[style + "_premises_correct"] = premises for layer in range(model.effective_depth): for component in ("mlp_delta", "postresidual"): for position in (2, 1): key = f"{style}_layer{layer}_{component}_pos{position}" patch = { (layer, component, position): donor_cache[component][layer, :, position] } prediction, probability = _patched_generation(model, tokens[valid], patch) raw[key + "_selected_query_indices"] = selected raw[key + "_predictions"] = prediction raw[key + "_answer_probabilities"] = probability following = prediction[:, 0] == expected correct = prediction[:, 0] == rows[valid, -1] base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) if style == "self" and not np.array_equal(prediction, base_pred): raise ValueError("Pure-first-hop self patch changes generation") record = { "donor": style, "execution": layer, "component": component, "position": position, "n": len(selected), "selected_query_coverage": len(selected) / len(rows), "full_pool_coverage": len(selected) / len(world["familiar_2"]), "new_route_answer_accuracy": _mean(following), "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), "baseline_correct_coverage": _mean(base_correct), "all_required_atomic_correct_coverage": _mean(premises), "new_route_conditional_on_required_atomics": _mean( (following & (prediction[:, 1] == EOS))[premises] ), "new_route_conditional_on_baseline_correct": _mean( (following & (prediction[:, 1] == EOS))[base_correct] ), } records.append(record) with torch.no_grad(): entity_embedding = model.token.weight[ ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] ] normalized = F.normalize(entity_embedding, dim=-1) raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() raw["entity_embedding_singular_values"] = ( torch.linalg.svdvals(entity_embedding).cpu().numpy() ) np.savez_compressed(out / "trace-raw.npz", **raw) report = { "phase": "development", "created_utc": utc(), "baseline": baseline, "query_selection": ( "First 128 familiar_2 rows in frozen data order, independent of predictions" ), "selected_queries": len(rows), "full_pool_queries": len(world["familiar_2"]), "selection_coverage": len(rows) / len(world["familiar_2"]), "forward_max_absolute_difference": difference, "forward_all_argmax_identical": True, "donor_information": ( "Only BOS, head, first relation, SEP; no second relation or final answer" ), "patch_position_roles": {"1": "head control", "2": "first relation"}, "interventions": records, "wall_seconds": time.perf_counter() - started, "limits": [ "Unfitted final-norm tied readout and raw cosine are descriptive", "Attention maps are descriptive; patch tests entire state or MLP contribution", "Layers, positions and queries are dependent measurements in one world", ], } write_json(out / "trace-summary.json", report) return report
def edit_cases(world, n_facts=8, replay_n=32): """Choose graph-based first-hop edits before observing any model behavior.""" atoms = world["atomic"] lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) cases = [] for index in order: h, relation, old_bridge = map(int, atoms[index]) if (h, relation) not in candidate_first: continue first_rows = world["familiar_2"][ (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) ] bridges = sorted({int(t) for _, _, t in atoms}) new_bridge = next( ( b for b in bridges if b != old_bridge and all( (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) for row in first_rows ) ), None, ) if new_bridge is None: continue replay_indices = np.asarray([i for i in order if i != index][:replay_n]) if len(replay_indices) != replay_n: raise ValueError("Insufficient nonedited replay atoms") new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) old_fact = atoms[index : index + 1].copy() edited_lookup = {**lookup, (h, relation): new_bridge} tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} original_d_rows = {} unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] tasks["U_atomic"] = atoms[unreplayed].copy() successor_keys = set() for split in ("familiar_2", "strict_2"): rows = world[split] nodes, path_indices = truth_path_details(world, rows) first = path_indices[:, 0] == index second = (path_indices[:, 1] == index) & ~first unaffected = ~(first | second) for role, mask in (("first", first), ("second", second)): changed = rows[mask].copy() for i, row in enumerate(changed): bridge = edited_lookup[(int(row[0]), int(row[1]))] changed[i, -1] = edited_lookup[(bridge, int(row[2]))] if role == "first" and (bridge, int(row[2])) != (h, relation): successor_keys.add((bridge, int(row[2]))) tasks[f"D_{role}_{split}"] = changed original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() tasks["U_" + split] = rows[unaffected].copy() # All facts occurring as either hop in U retain their graph labels. if index in path_indices[unaffected]: raise ValueError("Edited fact leaked into the unaffected holdout") del nodes successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() cases.append( { "atomic_index": index, "old_fact": old_fact[0].tolist(), "new_fact": new_fact[0].tolist(), "replay_indices": replay_indices.tolist(), "tasks": tasks, "original_d_rows": original_d_rows, "propagation_scope": { name: { "n": len(old_rows), "changed_answer_n": int( np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) ), "source_pool_n": len(world[name.split("_", 2)[2]]), } for name, old_rows in original_d_rows.items() }, } ) if len(cases) == n_facts: break if len(cases) != n_facts: raise ValueError("Fewer graph-valid fixed edit cases than requested") return cases
def _atomic_loss(model, rows, world, device): tokens, labels = pack_rows(rows, separator=_separator(world)) tokens = torch.as_tensor(tokens, device=device) labels = torch.as_tensor(labels, device=device) logits = model(tokens) return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): """Independently edit one checkpoint; only unique block-0 MLP down changes.""" if arm not in {"edit", "review"}: raise ValueError("Arm must be edit or review") if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: raise ValueError("Nodes must be increasing with initial measurement") edited = copy.deepcopy(model).eval() target_name = "blocks.0.mlp.down.weight" for name, parameter in edited.named_parameters(): parameter.requires_grad_(name == target_name) parameter.grad = None before = {name: value.detach().clone() for name, value in edited.state_dict().items()} parameter = dict(edited.named_parameters())[target_name] optimizer = torch.optim.Adam([parameter], lr=lr) objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) history, raw = [], {} for name, old_rows in case["original_d_rows"].items(): raw[name + "_original_rows"] = old_rows raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] step = 0 final_loss = None for node in nodes: while step < node: optimizer.zero_grad(set_to_none=True) loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) loss.backward() optimizer.step() step += 1 final_loss = float(loss.detach()) measures = {} for name, rows in case["tasks"].items(): metrics, prediction = generate(edited, rows, world, device) if name in case["original_d_rows"]: old_rows = case["original_d_rows"][name] changed_mask = rows[:, -1] != old_rows[:, -1] predicted = prediction["predictions"] correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) metrics.update( { "changed_answer_n": int(changed_mask.sum()), "changed_answer_coverage": _mean(changed_mask), "changed_answer_accuracy": _mean(correct[changed_mask]), "old_answer_accuracy": _mean(old_correct), } ) measures[name] = metrics raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) history.append({"step": step, "loss": final_loss, "metrics": measures}) changed = [ name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) ] if set(changed) - {target_name}: raise ValueError("Parameters outside the frozen MLP projection changed") delta = parameter.detach() - before[target_name] raw["mlp_down_weight_delta"] = delta.cpu().numpy() return { "arm": arm, "atomic_index": case["atomic_index"], "old_fact": case["old_fact"], "new_fact": case["new_fact"], "replay_indices": case["replay_indices"], "propagation_scope": case["propagation_scope"], "updated_parameter": target_name, "changed_state_tensors": changed, "weight_delta_l2": float(delta.norm()), "history": history, }, raw
def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): out = Path(out) out.mkdir(parents=True, exist_ok=False) started = time.perf_counter() cases = edit_cases(world, n_facts=n_facts) serializable_cases = [ {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} for case in cases ] # This is written before evaluating or updating any case. write_json(out / "data-selected-edit-cases.json", serializable_cases) records = [] for number, case in enumerate(cases): for arm in ("edit", "review"): record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) write_json(out / f"case{number:02d}-{arm}.json", record) records.append(record) report = { "phase": "development", "created_utc": utc(), "n_facts": n_facts, "nodes": list(nodes), "lr": lr, "optimizer": "Adam, no weight decay", "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", "trained_compositions": 0, "unique_block_edited": 0, "executions_affected_by_shared_edit": model.repeats, "independent_layers": len(model.blocks), "execution_depth": model.effective_depth, "scope_difference": ( "Loop block-0 update applies at every repeat; ordinary block-0 applies once" ), "records": records, "wall_seconds": time.perf_counter() - started, "limits": [ "Edits use the same fixed budget; failed target changes remain in results", "MLP-only parameter fine-tuning is not a constrained-preservation theorem", "Each case independently starts from the same checkpoint", "A single development world is not independent confirmation", ], } write_json(out / "edit-summary.json", report) return report
def load_run(run_dir, checkpoint, device): run_dir, checkpoint = Path(run_dir), Path(checkpoint) saved = torch.load(checkpoint, map_location=device, weights_only=False) model = construct(saved["spec"], device).eval() model.load_state_dict(saved["model"], strict=True) arrays = np.load(run_dir / "world.npz", allow_pickle=False) world = {key: arrays[key] for key in arrays.files} world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) from .depth_step import audit_world
audit = audit_world(world) if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): raise ValueError("Checkpoint and archived data digest disagree") return ( model, world, { "checkpoint": str(checkpoint), "checkpoint_sha256": file_hash(checkpoint), "step": saved["step"], "spec": saved["spec"], "dataset_sha256": audit["dataset_sha256"], }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298"""W&B sidecar for future experiments; reads trainer artifacts without changing training."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport importlibimport jsonimport mathimport osimport subprocessimport sysimport timefrom pathlib import Path
DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json"PRIVATE_KEYS = { "api_key", "wandb_api_key", "access_token", "auth_token", "password", "credentials", "secret",}
def read_json(path): return json.loads(Path(path).read_text())
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix(".tmp") temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") temp.replace(path)
def public_config(value): if isinstance(value, dict): return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} if isinstance(value, list): return [public_config(v) for v in value] return value
def numeric_fields(value, prefix): result = {} for key, item in value.items(): name = f"{prefix}/{key}" if isinstance(item, dict): result.update(numeric_fields(item, name)) elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): result[name] = item return result
def learning_metrics(record, previous=None): """Keep the actual optimizer step and task denominators; derive interval throughput.""" result = {"training/step": int(record["step"])} result.update(numeric_fields(record.get("metrics", {}), "eval")) groups = { "training_seconds": "perf/training_seconds", "wall_seconds": "perf/wall_seconds", "examples": "exposure/examples", "supervised_tokens": "exposure/supervised_tokens", "executed_input_tokens": "compute/executed_input_tokens", "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", "atomic_epochs": "exposure/atomic_epochs", "composition_epochs": "exposure/composition_epochs", } for key, value in record.items(): if key in {"step", "metrics"}: continue if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): result[groups.get(key, f"training/{key}")] = value if previous is not None and record["step"] > previous["step"]: steps = record["step"] - previous["step"] if "training_seconds" in record and "training_seconds" in previous: seconds = record["training_seconds"] - previous["training_seconds"] if seconds > 0: result["perf/training_ms_per_update"] = 1000 * seconds / steps result["perf/updates_per_second"] = steps / seconds if "examples" in record and "examples" in previous: result["perf/examples_per_second"] = ( record["examples"] - previous["examples"] ) / seconds return result
class ArtifactRunTracker: def __init__(self, sdk, batch, path, settings): self.path = Path(path) self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" self.metadata = read_json(self.path / "run.json") self.settings = settings identity = { "batch": Path(batch).name, "name": self.path.name, "spec": public_config(self.metadata.get("spec", {})), "world_sha256": self.metadata.get("world_sha256"), "initial_model_sha256": self.metadata.get("initial_model_sha256"), } fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() saved = read_json(self.state_path) if self.state_path.exists() else {} if saved: assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] self.state = { "run_id": fingerprint[:16], "fingerprint": fingerprint, "entity": settings["entity"], "project": settings["project"], "last_logged_step": -1, **saved, } options = {"disable_git": True} if not settings["system_metrics"]: options["x_disable_stats"] = True else: if "gpu" in self.metadata: options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) if "pid" in self.metadata: options["x_stats_pid"] = self.metadata["pid"] mode = settings["mode"] run_id = self.state["run_id"] if mode == "offline" and saved: segment = saved.get("offline_segment", 0) + 1 self.state["offline_segment"] = segment run_id = f"{run_id[:12]}{segment:04x}" self.state_path.parent.mkdir(parents=True, exist_ok=True) config = { **identity, "scientific_run_id": self.state["run_id"], **{ k: self.metadata[k] for k in [ "model", "phase", "evaluation_nodes", "execution_lock_sha256", "parameters", "vocab_size", "atomic_examples", "composition_examples", "dtype", "gpu_name", ] if k in self.metadata }, } self.run = sdk.init( entity=settings["entity"], project=settings["project"], group=self.metadata.get("tracking_group", Path(batch).name), name=self.path.name, id=run_id, config=config, mode=mode, resume="allow" if mode == "online" else None, job_type=self.metadata.get("job_type", "training"), tags=self.metadata.get("tags", []), dir=str(self.state_path.parent), save_code=False, reinit="create_new", settings=sdk.Settings(**options), ) self.run.define_metric("training/step") self.run.define_metric("*", step_metric="training/step") if mode == "online": # The public history is authoritative: an SDK restart can briefly report step 0, # and a local cursor can include points queued before a network interruption. remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") self.cursor = remote.lastHistoryStep else: self.cursor = self.state["last_logged_step"] self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) write_json(self.state_path, self.state)
def poll(self): history = read_json(self.path / "learning.json") previous = None for record in history: step = int(record["step"]) if step > self.cursor: self.run.log(learning_metrics(record, previous), step=step) self.cursor = step self.state["last_logged_step"] = step write_json(self.state_path, self.state) previous = record status_path = self.path / "status.json" if status_path.exists(): status = read_json(status_path) self.run.summary["training_state"] = status.get("state", "unknown") complete = (self.path / "complete.json").exists() failure_record = (self.path / "failure.json").exists() or ( self.path / "failure-detail.json" ).exists() failed = failure_record and not complete self.run.summary["has_failure_record"] = failure_record self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() if complete or failed: self.run.summary["scientific_final_step"] = self.cursor self.run.finish(exit_code=1 if failed else 0) return True return False
def close(self): self.run.finish()
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, required=True) parser.add_argument("--runs-dir", type=Path) parser.add_argument("--defaults", type=Path, default=DEFAULTS) parser.add_argument("--entity") parser.add_argument("--project") parser.add_argument("--mode", choices=["online", "offline"]) parser.add_argument("--once", action="store_true") parser.add_argument("--detach", action="store_true") args = parser.parse_args() settings = read_json(args.defaults) for name in ["entity", "project", "mode"]: settings[name] = ( getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] ) if not settings["enabled"]: raise SystemExit("Experiment tracking is disabled in the selected defaults") local = args.root / "tracking-wandb" local.mkdir(parents=True, exist_ok=True) if args.detach: metadata_path = local / "process.json" if metadata_path.exists(): pid = read_json(metadata_path)["pid"] try: os.kill(pid, 0) except ProcessLookupError: pass else: raise SystemExit(f"Tracking process already running: {pid}") arguments = [a for a in sys.argv[1:] if a != "--detach"] command = [ sys.executable, "-u", "-m", "llm_memory_editability.experiment_tracking", *arguments, ] with (local / "tracker.log").open("a") as log: process = subprocess.Popen( command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True ) write_json(metadata_path, {"pid": process.pid, "command": command}) print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) return try: sdk = importlib.import_module("wandb") except ImportError as error: raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error with (local / "tracker.lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) active, finished = {}, set() runs_dir = args.runs_dir or args.root / "development" try: while True: for path in sorted(runs_dir.glob("*")): if path in active or path in finished: continue if not (path / "run.json").exists() or not (path / "learning.json").exists(): continue active[path] = ArtifactRunTracker(sdk, args.root, path, settings) print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) for path, tracker in list(active.items()): current = read_json(path / "run.json") if current.get("pid") != tracker.metadata.get("pid"): tracker.close() tracker = ArtifactRunTracker(sdk, args.root, path, settings) active[path] = tracker if tracker.poll(): finished.add(path) del active[path] if args.once: break manifest = args.root / "controller-state.json" if manifest.exists() and not active: if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: break time.sleep(settings["poll_seconds"]) finally: for tracker in active.values(): tracker.close()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839"""Deterministic analytical illustration from the supplied research memo."""
import platformfrom typing import Any
import numpy as np
from .low_rank import evaluate_update
def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: """Compare a shared-rule update with a one-entry exception.
At rank budget one, both changes have rank-one deltas but only the rule's target is representable. At budget two, both targets are representable. This is a classical matrix fact, not evidence of LLM editing difficulty. """ original = np.ones((2, 2), dtype=float) cases = { "original": evaluate_update(original, original, rank, atol), "rule": evaluate_update(original, 2 * original, rank, atol), "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), } return { "experiment": "minimal_low_rank", "scope": ( "Analytical SVD illustration for fully observed real matrices with a " "fixed total rank budget and unweighted Frobenius error. No training, " "optimization path, or Transformer editing is evaluated. Numerical " "rank counts singular values greater than an absolute tolerance; " "this example does not validate the broader research hypothesis." ), "parameters": { "rank_budget": cases["original"]["rank_budget"], "atol": cases["original"]["atol"], }, "versions": {"python": platform.python_version(), "numpy": np.__version__}, "cases": cases, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024).
Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c.The compact vocabulary, widths and data sizes are explicit experimental adaptations.CUDA Graph capture is an execution optimization, not a change to the training objective."""
from __future__ import annotations
import copyimport hashlibimport jsonimport mathimport timefrom datetime import datetime, timezonefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import CausalLM, ModelConfig, matmul_flops
def utc(): return datetime.now(timezone.utc).isoformat()
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") tmp.replace(path)
class SmallGPT(CausalLM): """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout."""
def __init__(self, config, dropout=0.1): super().__init__(config) self.dropout = dropout
def forward(self, tokens, positions=None): p = self.dropout if self.training else 0.0 x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) x = F.dropout(x, p=p, training=self.training) for block in self.blocks: z = block.ln1(x) batch, length, width = z.shape a = block.attention q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) y = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=p, ) y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + F.dropout(y, p=p, training=self.training) x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) x = self.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] return F.linear(x, self.token.weight)
def pack_rows(rows): """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" rows = np.asarray(rows, dtype=np.int64) x = np.zeros((len(rows), 4), dtype=np.int64) x[:, : rows.shape[1]] = rows positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] return x, positions, labels
def make_optimizer(model, lr, weight_decay): decay = [p for p in model.parameters() if p.ndim >= 2] no_decay = [p for p in model.parameters() if p.ndim < 2] return torch.optim.AdamW( [ {"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}, ], lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=True, capturable=True, )
class GraphStep: """Capture complete AdamW step and undo warmup without rebinding state tensors."""
def __init__(self, model, optimizer, table, batch_size, clip=1.0): self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip weights = {k: v.detach().clone() for k, v in model.state_dict().items()} state = { p: { k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) for k, v in s.items() } for p, s in optimizer.state.items() } cpu_rng = torch.get_rng_state() cuda_rng = torch.cuda.get_rng_state(table[0].device) torch.cuda.synchronize() stream = torch.cuda.Stream() stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(stream): for _ in range(3): self.eager() torch.cuda.current_stream().wait_stream(stream) torch.cuda.synchronize() self.graph = torch.cuda.CUDAGraph() with torch.cuda.graph(self.graph): self.loss, self.grad_norm = self.eager() torch.cuda.synchronize() with torch.no_grad(): for k, v in model.state_dict().items(): v.copy_(weights[k]) for param, values in optimizer.state.items(): before = state.get(param, {}) for k, v in values.items(): if torch.is_tensor(v): if k in before: v.copy_(before[k]) else: v.zero_() for p in model.parameters(): if p.grad is not None: p.grad.zero_() torch.set_rng_state(cpu_rng) torch.cuda.set_rng_state(cuda_rng, table[0].device)
def eager(self): self.optimizer.zero_grad(set_to_none=False) x, pos, labels = (t[self.index] for t in self.table) logits = self.model(x, positions=pos) loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def __call__(self, indices): self.index.copy_(indices) self.graph.replay() return self.loss
class EpochStream: """Uniform shuffled epochs of the combined atomic/composite training set."""
def __init__(self, size, seed): self.size = size self.rng = np.random.default_rng(seed) self.remaining = np.empty(0, dtype=np.int64)
def take(self, n): parts = [] while n: if not len(self.remaining): self.remaining = self.rng.permutation(self.size) count = min(n, len(self.remaining)) parts.append(self.remaining[:count]) self.remaining = self.remaining[count:] n -= count return np.concatenate(parts)
def state_dict(self): return { "size": self.size, "rng": self.rng.bit_generator.state, "remaining": self.remaining.copy(), }
def load_state_dict(self, state): assert state["size"] == self.size self.rng.bit_generator.state = state["rng"] self.remaining = state["remaining"].copy()
@torch.no_grad()def evaluate_rows(model, rows, device, batch_size=1024): model.eval() packed = pack_rows(rows) answers, stops, losses = [], [], [] for start in range(0, len(rows), batch_size): x, pos, labels = ( torch.as_tensor(t[start : start + batch_size], device=device) for t in packed ) logits = model(x, pos) losses.append( F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") .view(-1, 2) .cpu() .numpy() ) answer = logits[:, 0].argmax(-1) # Actual generated answer is fed back when producing EOS. x[torch.arange(len(x), device=device), pos[:, 1]] = answer stop = model(x, pos)[:, 1].argmax(-1) answers.append(answer.cpu().numpy()) stops.append(stop.cpu().numpy()) model.train() if not len(rows): return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) correct = answer == rows[:, -1] return { "n": len(rows), "answer_accuracy": float(correct.mean()), "accuracy": float((correct & (stop == 1)).mean()), "nll": float(nll.mean()), }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]}
@torch.no_grad()def two_calls(model, rows, device): if not len(rows): return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] _, first_pred = evaluate_rows(model, first, device) second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] result, second_pred = evaluate_rows(model, second, device) result["accuracy"] = float( ( (second_pred["answer"] == rows[:, -1]) & (second_pred["stop"] == 1) & (first_pred["stop"] == 1) ).mean() ) return result
def source_hash(paths): return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths}
def run(spec, world, out, device="cuda:0", resume=False): """Run a fixed scientific budget. Intermediate evaluations never change training.""" out = Path(out) out.mkdir(parents=True, exist_ok=True) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.manual_seed(spec["initialization"]) torch.cuda.manual_seed_all(spec["initialization"]) device = torch.device(device) torch.cuda.set_device(device) cfg = ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) model = SmallGPT(cfg, spec["dropout"]).to(device) lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) opt = make_optimizer(model, lr, spec["weight_decay"]) atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) table = tuple( torch.as_tensor(np.concatenate([a, c]), device=device) for a, c in zip(atoms, comps, strict=True) ) stream = EpochStream(len(table[0]), spec["stream_seed"]) counts = {"atomic": 0, "composite": 0} elapsed_training, elapsed_eval = 0.0, 0.0 start_step = 0 checkpoint = out / "latest.pt" if resume: state = torch.load(checkpoint, map_location=device, weights_only=False) assert state["spec"] == spec model.load_state_dict(state["model"]) opt.load_state_dict(state["optimizer"]) # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. lr = opt.param_groups[0]["lr"] for group in opt.param_groups: group["lr"] = lr stream.load_state_dict(state["stream"]) counts = state["counts"] elapsed_training = state["elapsed_training"] elapsed_eval = state["elapsed_eval"] start_step = state["step"] torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) started = time.perf_counter() graph = GraphStep(model, opt, table, spec["batch_size"]) capture_seconds = time.perf_counter() - started names = ("atomic", "train_composite", "test_composite", "ood_composite") nparams = sum(p.numel() for p in model.parameters()) flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) rows_log = [] if (out / "learning.json").exists(): rows_log = json.loads((out / "learning.json").read_text()) if resume: # A crash can leave a log newer than the atomically replaced checkpoint. rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) rows_log.sort(key=lambda r: r["step"]) if start_step == spec["steps"]: endpoint = rows_log[-1] write_json( out / "complete.json", { "finished_utc": utc(), "spec": spec, "parameters": nparams, "training_seconds": elapsed_training, "evaluation_seconds": elapsed_eval, "endpoint": endpoint, "completion_recovered_from_final_checkpoint": True, }, ) write_json( out / "status.json", { "state": "complete", "step": start_step, "budget": spec["steps"], "updated_utc": utc(), "atomic": endpoint["atomic"]["accuracy"], "train": endpoint["train_composite"]["accuracy"], "test": endpoint["test_composite"]["accuracy"], }, ) return rows_log[-1]
def measure(step, last_loss=None): nonlocal elapsed_eval torch.cuda.synchronize() t0 = time.perf_counter() row = { "step": step, "utc": utc(), "parameters": nparams, "training_seconds": elapsed_training, "capture_seconds": capture_seconds, "examples": step * spec["batch_size"], "counts": counts.copy(), "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, "supervised_tokens": step * spec["batch_size"] * 2, "estimated_training_flops": step * flop_step, "last_batch_loss": last_loss, } predictions = {} for name in names: row[name], pred = evaluate_rows(model, world[name], device) predictions.update({name + "_" + k: v for k, v in pred.items()}) row["two_calls"] = two_calls(model, world["test_composite"], device) torch.cuda.synchronize() elapsed_eval += time.perf_counter() - t0 row["evaluation_seconds"] = elapsed_eval rows_log.append(row) write_json(out / "learning.json", rows_log) np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) state = { "step": step, "spec": spec, "model": model.state_dict(), "optimizer": opt.state_dict(), "stream": stream.state_dict(), "counts": counts, "elapsed_training": elapsed_training, "elapsed_eval": elapsed_eval, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(checkpoint) if step in spec["weight_nodes"]: torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"weights-{step:07d}.pt", ) status = { "state": "complete" if step == spec["steps"] else "running", "step": step, "budget": spec["steps"], "updated_utc": utc(), "atomic": row["atomic"]["accuracy"], "train": row["train_composite"]["accuracy"], "test": row["test_composite"]["accuracy"], } write_json(out / "status.json", status) print(json.dumps(status), flush=True) return row
if not resume: measure(0) nodes = [s for s in spec["nodes"] if s > start_step] for end in nodes: last_loss = None torch.cuda.synchronize() t0 = time.perf_counter() step = start_step while step < end: n = min(512, end - step) ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) atom_count = int((ix < len(world["atomic"])).sum()) counts["atomic"] += atom_count counts["composite"] += ix.size - atom_count gpu_ix = torch.as_tensor(ix, device=device) for j in range(n): lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) last_loss = graph(gpu_ix[j]) step += n torch.cuda.synchronize() elapsed_training += time.perf_counter() - t0 loss_value = float(last_loss.detach()) if not math.isfinite(loss_value): raise FloatingPointError(f"Nonfinite loss at step {end}") row = measure(end, loss_value) start_step = end write_json( out / "complete.json", { "finished_utc": utc(), "spec": spec, "parameters": nparams, "training_seconds": elapsed_training, "evaluation_seconds": elapsed_eval, "endpoint": row, }, ) return row123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints.
Donors are selected from world facts before any model is loaded. The only donorinput is its two-token atomic query; second relations and answers never enter theforward pass that supplies the post-first-block residual state."""
from __future__ import annotations
import hashlibimport importlibimport jsonimport platformimport sysimport timeimport typesfrom collections import Counterfrom datetime import datetime, timezonefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
CONDITIONS = ( "baseline", "identity_r1", "different_bridge_r1", "same_bridge_r1", "different_bridge_h", "different_bridge_h_r1", "counterfactual_input",)DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction")
def utc(): return datetime.now(timezone.utc).isoformat()
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def read_json(path): return json.loads(Path(path).read_text())
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") temporary.replace(path)
def require(condition, message): if not condition: raise AssertionError(message)
def _frozen_modules(source_dir, metadata): """Verify all historical copies, then import exclusively from that snapshot.""" snapshot = source_dir / "source" copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} verified = {} for original, expected in metadata["files"].items(): matches = [ p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) ] require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") path = matches[0] actual = digest(path) require(actual == expected, f"historical source hash mismatch: {path}") verified[path.relative_to(snapshot).as_posix()] = actual configs = [snapshot / p for p in verified if p.startswith("configs/")] require(len(configs) == 1, "expected exactly one frozen configuration") frozen = read_json(configs[0]) require( {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], "historical metadata differs from its frozen configuration", ) package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] namespace = types.ModuleType(package) namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] sys.modules[package] = namespace training = importlib.import_module(package + ".grok_depth") data = importlib.import_module(package + ".grok_depth_data") return training, data, verified
def load_source_run(source_dir, step, device="cuda:0"): """Return a frozen model/world after source, world and checkpoint consistency checks.""" source_dir = Path(source_dir).resolve() metadata = read_json(source_dir / "metadata.json") spec = metadata["spec"] require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") training, data, verified = _frozen_modules(source_dir, metadata) require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") checkpoint_path = source_dir / f"weights-{step:07d}.pt" checkpoint_hash = digest(checkpoint_path) checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) require( checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" ) require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") if step == spec["steps"]: latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) require( latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" ) require( checkpoint["model"].keys() == latest["model"].keys() and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), "endpoint weights differ from latest checkpoint", ) del latest world_path = source_dir / "world.npz" world_hash = digest(world_path) with np.load(world_path, allow_pickle=False) as stored: world = {key: stored[key].copy() for key in stored.files} world["metadata"] = read_json(source_dir / "world-metadata.json") require(digest(world_path) == world_hash, "world changed while loading") audit = data.audit_world(world) require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") require( audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], "world content hash mismatch", ) rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") for key, array in world.items(): if key != "metadata": require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") cfg = training.ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) model = training.SmallGPT(cfg, spec["dropout"]).to(device) model.load_state_dict(checkpoint["model"], strict=True) model.eval() for parameter in model.parameters(): parameter.requires_grad_(False) provenance = { "source_dir": str(source_dir), "source_hashes": verified, "checkpoint_sha256": checkpoint_hash, "world_file_sha256": world_hash, "dataset_sha256": audit["dataset_sha256"], "world_audit": audit, "source_metadata_sha256": digest(source_dir / "metadata.json"), "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), "world_regenerated_identically": True, } return model, world, spec, provenance
def _choose(candidates, world_hash, seed, row, kind): """Content-based uniform deterministic selection; no model input is accepted.""" if not candidates: return None material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) rng = np.random.default_rng( int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") ) return sorted(candidates)[int(rng.integers(len(candidates)))]
def select_donors(world, seed): """Select once per test row; preserve all rows, masks and rejection counts.
Different-bridge candidates share r1, change h/b/t, have ID second facts, and yield a reserved-test or unused counterfactual. Same-bridge candidates may change r1; only their bridge, query distinctness and h != original t matter. No candidate is selected using model behavior. """ rows = world["test_composite"] n = len(rows) atoms = {tuple(map(int, row)) for row in world["id_atomic"]} lookup = {(h, r): t for h, r, t in atoms} held_out = { tuple(map(int, row)) for name in ("test_composite", "unused_composite") for row in world[name] } training = {tuple(map(int, row)) for row in world["train_composite"]} world_hash = world["metadata"]["dataset_sha256"] out = { "original_rows": rows.copy(), "original_bridge": np.full(n, -1, dtype=np.int64), "different_donor": np.full((n, 3), -1, dtype=np.int64), "same_donor": np.full((n, 3), -1, dtype=np.int64), "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), "different_valid": np.zeros(n, dtype=bool), "same_valid": np.zeros(n, dtype=bool), "different_reason": np.full(n, "", dtype="U64"), "same_reason": np.full(n, "", dtype="U64"), "different_candidate_count": np.zeros(n, dtype=np.int64), "same_candidate_count": np.zeros(n, dtype=np.int64), "same_relation_control": np.full(n, "missing", dtype="U24"), "different_nondegenerate": np.zeros(n, dtype=bool), } rejection_names = ( "same_head", "same_bridge", "missing_id_second_fact", "same_tail", "head_is_answer", "counterfactual_in_train", "counterfactual_not_held_out", ) for reason in rejection_names: out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) for index, row in enumerate(rows): h, r1, r2, tail = map(int, row) bridge = lookup[h, r1] require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") out["original_bridge"][index] = bridge candidates = [] for dh, dr, db in sorted(atoms): if dr != r1: continue dt = lookup.get((db, r2)) cf = (dh, r1, r2, dt) reason = ( "same_head" if dh == h else "same_bridge" if db == bridge else "missing_id_second_fact" if dt is None else "same_tail" if dt == tail else "head_is_answer" if dh in (tail, dt) else "counterfactual_in_train" if cf in training else "counterfactual_not_held_out" if cf not in held_out else None ) if reason: out["different_rejected_" + reason][index] += 1 else: candidates.append((dh, dr, db, dt)) donor = _choose(candidates, world_hash, seed, row, "different") out["different_candidate_count"][index] = len(candidates) if donor is None: out["different_reason"][index] = "no_candidate_after_registered_exclusions" else: dh, dr, db, dt = donor out["different_donor"][index] = dh, dr, db out["counterfactual_rows"][index] = dh, r1, r2, dt out["different_valid"][index] = True out["different_reason"][index] = "eligible" out["different_nondegenerate"][index] = db != dt and db != tail candidates = [ (dh, dr, db) for dh, dr, db in atoms if db == bridge and (dh, dr) != (h, r1) and dh != tail ] same_relation = [candidate for candidate in candidates if candidate[1] == r1] donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") out["same_candidate_count"][index] = len(candidates) if donor is None: out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" else: out["same_donor"][index] = donor out["same_valid"][index] = True out["same_reason"][index] = "eligible" out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" return out
@torch.no_grad()def traced_forward( model, tokens, positions=None, donor_state=None, patch_positions=(), identity=False, return_state=False,): """Frozen SmallGPT eval forward, replacing residuals after complete block 0.
Both attention and MLP in the first block run before replacement. There is no patch in another block, and final LN/output projection remain untouched. """ require(not model.training, "interventions require model.eval()") require( donor_state is None or not identity, "identity and donor patches are mutually exclusive" ) x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) first_state = None for index, block in enumerate(model.blocks): z = block.ln1(x) batch, length, width = z.shape attention = block.attention q, k, v = ( attention.qkv(z) .view(batch, length, 3, attention.heads, width // attention.heads) .unbind(2) ) y = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 ) y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + y x = x + block.mlp(block.ln2(x)) if index == 0: if return_state: first_state = x.clone() if donor_state is not None or identity: x = x.clone() replacement = x.clone() if identity else donor_state for position in patch_positions: x[:, position, :] = replacement[:, position, :] x = model.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] logits = F.linear(x, model.token.weight) return (logits, first_state) if return_state else logits
@torch.no_grad()def prefix_state(model, prefixes): """Two informative tokens, padded to the historical four-position shape.
Both suffix tokens are the fixed PAD token, never a relation or answer. Causality makes the retained two states independent of these suffixes. Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. """ require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") padded = F.pad(prefixes, (0, 2), value=0) _, state = traced_forward(model, padded, return_state=True) return state[:, :2]
@torch.no_grad()def evaluate_condition( model, rows, device, batch_size=1024, donor_prefixes=None, patch_positions=(), identity=False, verify_trace=False,): """Answer generation followed by EOS with the generated answer fed back.
The exact same prefix state is reapplied on the second forward pass. Arrays are local to the supplied rows; the caller scatters them to the full test set. """ n = len(rows) answers, stops, original_logits = [], [], [] trace_max_delta, trace_disagreements = 0.0, 0 prefix_max_delta = 0.0 for start in range(0, n, batch_size): selected = rows[start : start + batch_size] arity = rows.shape[1] require(arity in (3, 4), "expected atomic or composite rows") packed = np.zeros((len(selected), 4), dtype=np.int64) packed[:, :arity] = selected x = torch.as_tensor(packed, device=device) pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) donor_state = None if donor_prefixes is not None: prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") donor_state = prefix_state(model, prefixes) logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) if verify_trace: reference = model(x, pos) trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) prefix = prefix_state(model, x[:, :2]) _, whole = traced_forward(model, x, return_state=True) prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) require( torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), "pure-prefix state does not match causal full-input prefix", ) answer = logits[:, 0].argmax(-1) original_logits.append(logits[:, 0].cpu().numpy()) x[:, arity - 1] = answer generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) if verify_trace: reference = model(x, pos) trace_max_delta = max( trace_max_delta, float((reference - generated_logits).abs().max()) ) trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) answers.append(answer.cpu().numpy()) stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") return { "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), "answer_logits": np.concatenate(original_logits) if n else np.empty((0, model.token.num_embeddings), dtype=np.float32), }, { "standard_forward_max_logit_delta": trace_max_delta, "standard_forward_argmax_disagreements": trace_disagreements, "prefix_vs_full_first_block_max_delta": prefix_max_delta, "trace_comparison_performed": verify_trace, }
def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): count = int(selected.sum()) counterfactual = selected & cf_valid ncf = int(counterfactual.sum()) correct = answer == original cf_correct = answer == cf return { "n": count, "total_test_n": total, "coverage": count / total if total else None, "original_answer_accuracy": float(correct[selected].mean()) if count else None, "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) if count else None, "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) if count else None, "cf_target_n": ncf, "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) if ncf else None, }
def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" started = time.perf_counter() rows = world["test_composite"] n = len(rows) different, same = donors["different_valid"], donors["same_valid"] arrays = {key: value.copy() for key, value in donors.items()} audits = {} for condition in CONDITIONS: mask = ( same if condition == "same_bridge_r1" else different if condition.startswith("different_") or condition == "counterfactual_input" else np.ones(n, dtype=bool) ) eval_rows = ( donors["counterfactual_rows"][mask] if condition == "counterfactual_input" else rows[mask] ) donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None positions = ( (0, 1) if condition == "different_bridge_h_r1" else (0,) if condition == "different_bridge_h" else (1,) ) result, audit = evaluate_condition( model, eval_rows, device, batch_size, donor_prefix, positions, condition == "identity_r1", condition == "baseline", ) audits[condition] = audit answer = np.full(n, -1, dtype=np.int64) stop = np.full(n, -1, dtype=np.int64) answer[mask], stop[mask] = result["answer"], result["stop"] arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop arrays[condition + "_valid"] = mask original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] cf_logit = np.full(n, np.nan, dtype=np.float32) cf_local = different[mask] cf_logit[mask.nonzero()[0][cf_local]] = ( result["answer_logits"][ np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] ] - original_logit[cf_local] ) arrays[condition + "_cf_minus_original_logit"] = cf_logit for column in ("answer", "stop"): require( np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), f"identity patch changed {column}", ) if len(model.blocks) == 1: for condition in ( "different_bridge_r1", "same_bridge_r1", "different_bridge_h", "different_bridge_h_r1", ): valid = arrays[condition + "_valid"] require( np.array_equal( arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] ), f"one-layer structural negative control changed {condition}.{column}", ) baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) cf_correct = ( different & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) & (arrays["counterfactual_input_stop"] == 1) ) atomic_rows = { "different_first": (donors["different_donor"], different), "counterfactual_second": ( np.c_[ donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] ], different, ), "same_first": (donors["same_donor"], same), } atomic_scores = {} atomic_correct = {} for name, (facts, mask) in atomic_rows.items(): prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) answer = np.full(n, -1, dtype=np.int64) stop = np.full(n, -1, dtype=np.int64) answer[mask], stop[mask] = prediction["answer"], prediction["stop"] arrays["atomic_" + name + "_rows"] = facts.copy() arrays["atomic_" + name + "_answer"] = answer arrays["atomic_" + name + "_stop"] = stop arrays["atomic_" + name + "_valid"] = mask.copy() correct = mask & (answer == facts[:, -1]) atomic_correct[name] = correct & (stop == 1) count = int(mask.sum()) atomic_scores[name] = { "n": count, "total_test_n": n, "coverage": count / n if n else None, "answer_accuracy": float(correct[mask].mean()) if count else None, "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, } groups = { "all_test": np.ones(n, dtype=bool), "different_donor_available": different, "same_donor_available": same, "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, "different_bridge_nondegenerate": donors["different_nondegenerate"], "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] & atomic_correct["counterfactual_second"], } for group, mask in groups.items(): arrays["subset_" + group] = mask scores = { group: { "subset_n": int(mask.sum()), "total_test_n": n, "coverage": float(mask.mean()) if n else None, "conditions": { condition: _metrics( arrays[condition + "_answer"], arrays[condition + "_stop"], rows[:, -1], donors["counterfactual_rows"][:, -1], mask & arrays[condition + "_valid"], different, n, arrays["baseline_answer"], ) for condition in CONDITIONS }, } for group, mask in groups.items() } summary = { "conditions": list(CONDITIONS), "scores": scores, "atomic_preconditions": atomic_scores, "donor_coverage": { "total_test_n": n, "different_n": int(different.sum()), "same_n": int(same.sum()), "different_reasons": dict(Counter(donors["different_reason"].tolist())), "same_reasons": dict(Counter(donors["same_reason"].tolist())), "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), }, "engineering_checks": { "identity_predictions_equal": True, "one_layer_all_early_position_patch_predictions_equal": True if len(model.blocks) == 1 else None, "trace": audits["baseline"], "eos_uses_generated_answer_and_reapplies_patch": True, "donor_nonpadding_input_tokens": 2, "donor_forward_sequence_length": 4, "donor_pad_token": 0, }, "evaluation_seconds": time.perf_counter() - started, } return summary, arrays
def environment(device): return { "python": platform.python_version(), "platform": platform.platform(), "torch": torch.__version__, "numpy": np.__version__, "cuda": torch.version.cuda, "device": str(device), "gpu": torch.cuda.get_device_name(torch.device(device)) if str(device).startswith("cuda") else None, "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, "cudnn_tf32": torch.backends.cudnn.allow_tf32, "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb.
Source: https://github.com/OSU-NLP-Group/GrokkedTransformerRevision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT).
The graph, atomic ID/OOD split, reserved ID test chains, and phi downsamplingfollow the authors' construction. Differences: integer tokens replace text;randomness is local and seeded; atomic ordering is stable; graph size and thereserved ID-test fraction are configurable. Unselected ID chains are returnedfor audit only. No graph is regenerated to improve OOD counts or model results.
Adapted source license:MIT LicenseCopyright (c) 2024 OSU Natural Language Processing
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE."""
from __future__ import annotations
import hashlibimport math
import numpy as np
PAD_TOKEN = 0EOS_TOKEN = 1ENTITY_OFFSET = 2SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer"SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c"ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic")COMPOSITE_SPLITS = ( "train_composite", "test_composite", "ood_composite", "unused_composite",)
def _array(rows: list, columns: int) -> np.ndarray: return np.asarray(rows, dtype=np.int64).reshape(-1, columns)
def build_world( seed: int, entities: int = 128, relations: int = 16, degree: int = 8, phi: float = 8.0, id_fraction: float = 0.95, id_test_fraction: float = 0.005,) -> dict: """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays.
All atomics belong in training, including those labelled OOD. OOD refers to *composition experience*: neither constituent of an OOD composite is allowed in composite training. Mixed ID/OOD chains are excluded. The test set is reserved before phi downsampling; unused ID chains are never automatically reassigned to test. ``phi`` is relative to ID atomics, as in the source. Requests larger than the available training pool are capped and explicitly recorded. Empty test sets are retained and reported.
Query tokens are every column except the last; the last is the entity answer. EOS supervision, padding, and loss masks belong to the trainer. """ for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: raise ValueError(f"{name} must be a positive integer") if degree > relations: raise ValueError("degree cannot exceed relations") if not math.isfinite(phi) or phi < 0: raise ValueError("phi must be finite and nonnegative") if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: raise ValueError("id_fraction must be in [0, 1]") if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: raise ValueError("id_test_fraction must be in [0, 1]")
# RandomState keeps the source's NumPy draw family, without global RNG use. rng = np.random.RandomState(seed) relation_offset = ENTITY_OFFSET + entities rows = [] outgoing = [[] for _ in range(entities)] for head_index in range(entities): selected = rng.choice(relations, size=degree, replace=False) for relation_index in selected: tail_index = int(rng.randint(entities)) edge = ( head_index + ENTITY_OFFSET, int(relation_index) + relation_offset, tail_index + ENTITY_OFFSET, ) outgoing[head_index].append(len(rows)) rows.append(edge) atomic = _array(rows, 3) ood_count = round(len(atomic) * (1 - id_fraction)) ood_mask = np.zeros(len(atomic), dtype=bool) ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True
eligible, test, ood = [], [], [] mixed_count = 0 for first_index, (head, relation1, bridge) in enumerate(atomic): for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: _, relation2, tail = atomic[second_index] row = (head, relation1, relation2, tail) first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] if first_ood and second_ood: ood.append(row) elif first_ood or second_ood: mixed_count += 1 elif rng.uniform() > id_test_fraction: eligible.append(row) else: test.append(row)
requested_count = round(phi * int((~ood_mask).sum())) train_count = min(requested_count, len(eligible)) # Source choose() returns the full pool unchanged when it is saturated. indices = ( np.arange(len(eligible)) if train_count == len(eligible) else rng.choice(len(eligible), size=train_count, replace=False) ) eligible_array = _array(eligible, 4) selected_mask = np.zeros(len(eligible), dtype=bool) selected_mask[indices] = True world = { "atomic": atomic, "id_atomic": atomic[~ood_mask], "ood_atomic": atomic[ood_mask], "train_composite": eligible_array[indices], "test_composite": _array(test, 4), "ood_composite": _array(ood, 4), "unused_composite": eligible_array[~selected_mask], "metadata": { "seed": int(seed), "entities": int(entities), "relations": int(relations), "degree": int(degree), "phi_requested": float(phi), "id_fraction": float(id_fraction), "id_test_fraction": float(id_test_fraction), "pad_token": PAD_TOKEN, "eos_token": EOS_TOKEN, "entity_offset": ENTITY_OFFSET, "relation_offset": int(relation_offset), "vocab_size": int(relation_offset + relations), "train_composite_requested": int(requested_count), "train_composite_capped": requested_count > len(eligible), "phi_actual": train_count / max(int((~ood_mask).sum()), 1), "mixed_composite_excluded": mixed_count, "source_url": SOURCE_URL, "source_commit": SOURCE_COMMIT, "source_file": "composition.ipynb", "source_license": "MIT", "construction_differences": [ "integer tokens and local seeded RNG", "stable atomic ordering instead of Python set iteration", "configurable graph size and ID-test reserve fraction", "all evaluation rows retained instead of sampling at most 3000", ], }, } audit = audit_world(world) world["metadata"]["counts"] = audit["counts"] world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] world["metadata"]["warnings"] = audit["warnings"] return world
def audit_world(world: dict) -> dict: """Validate token ranges, graph truth, exhaustive partitions and no leakage.
Raises ValueError on a broken contract; zero-sized test sets and capped training pools are valid and surfaced as warnings, never resampled. """ metadata = world["metadata"] entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) relation_offset = entities + ENTITY_OFFSET digest = hashlib.sha256() counts = {} tuples = {} for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: array = world[name] columns = 3 if name in ATOMIC_SPLITS else 4 if not isinstance(array, np.ndarray) or array.dtype != np.int64: raise ValueError(f"{name} must be an int64 numpy array") if array.ndim != 2 or array.shape[1] != columns: raise ValueError(f"{name} must have {columns} columns") for column in (0, columns - 1): if np.any(array[:, column] < ENTITY_OFFSET) or np.any( array[:, column] >= relation_offset ): raise ValueError(f"{name} has an invalid entity token") if np.any(array[:, 1:-1] < relation_offset) or np.any( array[:, 1:-1] >= relation_offset + relations ): raise ValueError(f"{name} has an invalid relation token") rows = {tuple(map(int, row)) for row in array} if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): raise ValueError(f"{name} has duplicate or conflicting queries") tuples[name] = rows counts[name] = len(array) digest.update(name.encode()) digest.update(np.asarray(array.shape, dtype="<i8").tobytes()) digest.update(array.astype("<i8", copy=False).tobytes())
atomics, id_atomics, ood_atomics = (tuples[name] for name in ATOMIC_SPLITS) if id_atomics & ood_atomics or id_atomics | ood_atomics != atomics: raise ValueError("ID/OOD atomics do not partition all atomic facts") if len(atomics) != entities * degree: raise ValueError("incorrect atomic graph size") outgoing = {} lookup = {} for head, relation, tail in atomics: outgoing.setdefault(head, []).append((relation, tail)) lookup[head, relation] = tail if len(outgoing) != entities or any(len(edges) != degree for edges in outgoing.values()): raise ValueError("incorrect per-entity out-degree")
id_chains, ood_chains, mixed_count = set(), set(), 0 for head, relation1, bridge in atomics: for relation2, tail in outgoing[bridge]: row = (head, relation1, relation2, tail) first_id = (head, relation1, bridge) in id_atomics second_id = (bridge, relation2, tail) in id_atomics if first_id and second_id: id_chains.add(row) elif not first_id and not second_id: ood_chains.add(row) else: mixed_count += 1 occupied = set() for name in COMPOSITE_SPLITS: rows = tuples[name] if rows & occupied: raise ValueError("composite splits overlap") occupied |= rows for head, relation1, relation2, tail in rows: bridge = lookup.get((head, relation1)) if bridge is None or lookup.get((bridge, relation2)) != tail: raise ValueError(f"{name} contains a false chain") expected = ood_chains if name == "ood_composite" else id_chains if not rows <= expected: raise ValueError(f"{name} contains chains from the wrong atomic split") returned_id = set().union( *(tuples[name] for name in COMPOSITE_SPLITS if name != "ood_composite") ) if returned_id != id_chains or tuples["ood_composite"] != ood_chains: raise ValueError("composite partitions omit eligible graph chains") if mixed_count != metadata["mixed_composite_excluded"]: raise ValueError("incorrect excluded mixed-chain count") warnings = [ f"{name} is empty" for name in ("test_composite", "ood_composite") if not counts[name] ] if metadata["train_composite_capped"]: warnings.append("requested phi exceeds available composite training pool") return { "ok": True, "counts": counts, "id_composite_total": len(id_chains), "ood_composite_total": len(ood_chains), "mixed_composite_excluded": mixed_count, "dataset_sha256": digest.hexdigest(), "warnings": warnings, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Frozen paired depth extension: validation and threshold accounting only."""
from __future__ import annotations
import hashlibimport jsonfrom pathlib import Path
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def read_json(path): return json.loads(Path(path).read_text())
def validate_pair(spec, baseline): """Only the layer count and bookkeeping phase may differ from the old baseline.""" assert baseline["layers"] == 2 assert spec["layers"] in (3, 4) ignored = {"layers", "phase"} assert {k: v for k, v in spec.items() if k not in ignored} == { k: v for k, v in baseline.items() if k not in ignored }, "Extension changes a non-depth training condition"
def threshold_time(rows, threshold, counts, budget): """First start of three registered consecutive nodes; never choose a best node.""" assert 0 <= threshold <= 1 steps = [row["step"] for row in rows] assert steps == sorted(set(steps)), "Unsorted or duplicate evaluation nodes" assert not steps or steps[-1] <= budget result = { "threshold": threshold, "reached": False, "step": None, "confirmed_at_step": None, "previous_evaluation_step": None, "examples": None, "atomic_exposures": None, "composite_exposures": None, "dataset_passes": None, "estimated_training_flops": None, "effective_input_tokens": None, "supervised_tokens": None, "last_observed_step": steps[-1] if steps else None, "budget_steps": budget, } for i in range(max(0, len(rows) - 2)): triple = rows[i : i + 3] if all(row["test_composite"]["accuracy"] >= threshold for row in triple): row = triple[0] result.update( reached=True, step=row["step"], confirmed_at_step=triple[-1]["step"], previous_evaluation_step=rows[i - 1]["step"] if i else None, examples=row["examples"], atomic_exposures=row["counts"]["atomic"] / counts["atomic"], composite_exposures=row["counts"]["composite"] / counts["train_composite"], dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), estimated_training_flops=row["estimated_training_flops"], effective_input_tokens=row["effective_input_tokens"], supervised_tokens=row["supervised_tokens"], ) break return result
def verify_files(root, expected): for relative, sha in expected.items(): assert digest(root / relative) == sha, f"Frozen input changed: {relative}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346"""Audited data and fixed atomic/composite exposure for loop-depth comparisons.
The graph, truth, complete-query holdout and phi sampling are inherited from``grok_multihop_data``. Changing the atomic ID fraction is an explicit designchoice; no graph is regenerated in response to diagnostics or model scores."""
from __future__ import annotations
import copyfrom collections.abc import Mapping
import numpy as np
from . import grok_multihop_data as multihop
SPLITS = multihop.SPLITSDATA_DEFAULTS = { "hops": 2, "entities": 128, "relations": 16, "degree": 8, "phi": 6.0, "id_fraction": 0.95, "id_test_fraction": 0.1, "evaluation_size": 1024,}
def build_world(spec: Mapping) -> dict: """Adapt a flat run specification while retaining the historical world API.
``world_seed`` (or ``seed``) is required. Unrelated model/training keys are ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit ``id_fraction=0.75`` for the new composition-experience comparison.
``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j fact in ``world['atomic']``. These truth indices are evaluation artifacts; training must only use the original atomic and train-composite rows. """ if "world_seed" not in spec and "seed" not in spec: raise ValueError("spec must contain world_seed or seed") seed = spec.get("world_seed", spec.get("seed")) fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} world = multihop.build_world(seed, **fields) world["relevant_atomic_indices"] = { name: query_atomic_indices(world, world[name]) for name in SPLITS } world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) world["metadata"]["loop_data_contract"] = { "constructor": "grok_multihop_data.build_world", "world_selection": "fixed supplied seed; no diagnostic or model-based selection", "all_atomic_rows_are_training_facts": True, "ood_definition": "all constituent facts absent from composite training by split", "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", } audit_world(world) return world
def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: """Return true constituent fact indices, including [N, 1] for atomics.""" meta = world["metadata"] _, edges = multihop.path_details( rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) ) return edges
def audit_world(world: dict) -> dict: """Independently verify truth, ID/OOD partitions and recorded fact indices.
The reused auditor checks truth by graph traversal and counts all-ID and all-OOD paths by dynamic programming, independently of path construction. Neither correct-looking diagnostics nor a saved metadata hash substitutes for those checks. """ result = multihop.audit_world(world) recorded = world.get("relevant_atomic_indices") if recorded is not None: if set(recorded) != set(SPLITS): raise ValueError("Relevant atomic indices must cover every data split") for name in SPLITS: expected = query_atomic_indices(world, world[name]) if ( not isinstance(recorded[name], np.ndarray) or recorded[name].dtype != np.int64 or not np.array_equal(recorded[name], expected) ): raise ValueError(f"Incorrect relevant atomic indices: {name}") if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): raise ValueError("Recorded dataset hash disagrees with actual data") return {**result, "relevant_atomic_indices_checked": recorded is not None}
def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: """Describe target concentration after omitting the head and prefix relations.
The empirical modal fraction sums each suffix group's largest target count and divides by query count. It uses the same rows to count and summarize; singleton suffixes score one automatically. It is not a model-independent generalization bound, a learned baseline, or proof that heads are unnecessary. """ results = [] n = len(rows) for length in range(1, rows.shape[1] - 1): suffix = rows[:, -(length + 1) : -1] if not n: results.append( { "suffix_relation_count": length, "groups": 0, "empirical_modal_target_fraction": None, "single_target_group_query_fraction": None, "singleton_group_query_fraction": None, "multi_query_groups": 0, "multi_query_coverage_fraction": None, "multi_query_empirical_modal_target_fraction": None, "multi_target_groups": 0, "same_suffix_different_target_example": None, } ) continue _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) maxima = np.zeros(len(totals), dtype=np.int64) np.maximum.at(maxima, pairs[:, 0], pair_counts) multi = totals > 1 multi_n = int(totals[multi].sum()) multi_target = maxima != totals example = None if multi_target.any(): # Deterministic first lexicographic suffix with incompatible targets. group = int(np.flatnonzero(multi_target)[0]) members = np.flatnonzero(groups == group) first = members[0] second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] example = [rows[first].tolist(), rows[second].tolist()] results.append( { "suffix_relation_count": length, "groups": len(totals), "empirical_modal_target_fraction": float(maxima.sum() / n), "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), "singleton_group_query_fraction": float((totals == 1).sum() / n), "multi_query_groups": int(multi.sum()), "multi_query_coverage_fraction": float(multi_n / n), "multi_query_empirical_modal_target_fraction": ( float(maxima[multi].sum() / multi_n) if multi_n else None ), "multi_target_groups": int(multi_target.sum()), "same_suffix_different_target_example": example, } ) return results
def majority_tail_diagnostics(rows: np.ndarray) -> dict: """Report the empirical within-split majority target, without fitting a model.""" if not len(rows): return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} targets, counts = np.unique(rows[:, -1], return_counts=True) index = int(counts.argmax()) return { "target_token": int(targets[index]), "count": int(counts[index]), "fraction": float(counts[index] / len(rows)), "distinct_targets": len(targets), }
def data_diagnostics(world: dict) -> dict: """Pure data coverage and target distributions; never evaluate a predictor.""" atomic_n = len(world["atomic"]) indices = world.get("relevant_atomic_indices") if indices is None: indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) id_facts = np.zeros(atomic_n, dtype=bool) id_facts[indices["id_atomic"].ravel()] = True training_majority = majority_tail_diagnostics(world["train_composite"]) per_split = {} for name in SPLITS: rows, edges = world[name], indices[name] distinct = np.unique(edges) trained = training_counts[edges] > 0 all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) per_split[name] = { "n": len(rows), "unique_relevant_atomic_facts": len(distinct), "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), "relevant_fact_occurrences_seen_in_composite_training_fraction": ( float(trained.mean()) if edges.size else None ), "all_id_queries": int(all_id.sum()), "all_ood_queries": int(all_ood.sum()), "mixed_queries": int((~all_id & ~all_ood).sum()), "unique_relevant_facts_by_hop": [ len(np.unique(edges[:, j])) for j in range(edges.shape[1]) ], "within_split_majority_tail": majority_tail_diagnostics(rows), "train_composite_majority_tail_fraction": ( float((rows[:, -1] == training_majority["target_token"]).mean()) if len(rows) and training_majority["target_token"] is not None else None ), "suffix_without_head": suffix_target_diagnostics(rows), } return { "interpretation": { "atomic_coverage": "data availability only; does not establish model mastery", "ood": "all facts are atomic training facts; none has composite-training experience", "suffix": ( "empirical within-split target concentration; singleton suffixes score 1; " "not a predictor, generalization bound, or evidence that the model ignores head" ), "majority": "within-split descriptive ceiling plus fixed training-majority fraction", }, "atomic_facts": atomic_n, "id_facts": int(id_facts.sum()), "ood_facts": int((~id_facts).sum()), "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), "train_composite_fact_occurrence_counts": training_counts.tolist(), "splits": per_split, }
class _EpochStream: """NumPy-only shuffled epochs, with the existing EpochStream draw convention."""
def __init__(self, size: int, seed): self.size = size self.rng = np.random.default_rng(seed) self.remaining = np.empty(0, dtype=np.int64)
def take(self, n: int) -> np.ndarray: if not n: return np.empty(0, dtype=np.int64) parts = [] while n: if not len(self.remaining): self.remaining = self.rng.permutation(self.size) count = min(n, len(self.remaining)) parts.append(self.remaining[:count]) self.remaining = self.remaining[count:] n -= count return np.concatenate(parts)
def state_dict(self) -> dict: return { "size": self.size, "rng": copy.deepcopy(self.rng.bit_generator.state), "remaining": self.remaining.copy(), }
def load_state_dict(self, state: dict): if state["size"] != self.size: raise ValueError("Epoch size mismatch") remaining = np.asarray(state["remaining"]) if ( remaining.ndim != 1 or remaining.dtype != np.int64 or np.any((remaining < 0) | (remaining >= self.size)) or len(np.unique(remaining)) != len(remaining) ): raise ValueError("Invalid remaining epoch indices") self.rng.bit_generator.state = copy.deepcopy(state["rng"]) self.remaining = remaining.copy()
class StratifiedStream: """Fixed composition per batch over the table [atomics; train_composites].
Atomic, composite and interleaving draws use independent RNGs. Thus changing phi or the composite pool cannot change the atomic sequence or its batch positions. Individual strata use shuffled epochs and may cross an epoch boundary within one batch. No evaluation data enters either stream. """
def __init__( self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int ): fields = { "atomic_size": atomic_size, "composite_size": composite_size, "batch_size": batch_size, "n_atomic": n_atomic, } for name, value in fields.items(): if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: raise ValueError(f"{name} must be a nonnegative integer") if batch_size < 1 or n_atomic > batch_size: raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): raise ValueError("A sampled stratum cannot be empty") self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) self.batches = 0
def take(self, n: int | None = None) -> np.ndarray: if n is not None and n != self.batch_size: raise ValueError("StratifiedStream only emits its configured batch_size") indices = np.r_[ self.atomic.take(self.n_atomic), self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, ] self.batches += 1 return indices[self.interleave.permutation(self.batch_size)]
def state_dict(self) -> dict: return { "version": 1, "atomic_size": self.atomic_size, "composite_size": self.composite_size, "batch_size": self.batch_size, "n_atomic": self.n_atomic, "atomic": self.atomic.state_dict(), "composite": self.composite.state_dict(), "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), "batches": self.batches, }
def load_state_dict(self, state: dict): if state.get("version") != 1: raise ValueError("Unsupported StratifiedStream state version") for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): if state[name] != getattr(self, name): raise ValueError(f"StratifiedStream {name} mismatch") atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) interleave = copy.deepcopy(self.interleave) atomic.load_state_dict(state["atomic"]) composite.load_state_dict(state["composite"]) interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) batches = state["batches"] if not isinstance(batches, int) or batches < 0: raise ValueError("Invalid completed batch count") self.atomic, self.composite, self.interleave = atomic, composite, interleave self.batches = batches123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549"""Prefix-only component interventions at every executed Transformer block.
The recipient block runs normally before mixing cached attention and MLPincrements at r1. The current block's MLP is never recomputed after mixing.Only later blocks consume the intervention. Donors are graph-selected beforeevaluating the model and receive only [head, r1] followed by fixed PAD tokens."""
from __future__ import annotations
import hashlibimport jsonimport timefrom collections import Counter, defaultdictfrom numbers import Integral
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_multihop import pack_rows
COMPONENTS = ("attention", "mlp", "both", "full")SPLITS = ("test_composite", "test_full_composite", "ood_composite")TRACE_FIELDS = ("input", "attention", "mlp", "residual")
def _choose(candidates, world_hash, seed, row, family): if not candidates: return None material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) return sorted(candidates)[index]
def _path(head, relations, graph): edges = [] for relation in relations: fact = graph.get((int(head), int(relation))) if fact is None: return None head, index = fact edges.append(index) return int(head), tuple(edges)
def select_donors(world, seed, split="test_composite"): """Select same-r1 donors using only truth and split membership.
ID recipients and every donor-path fact are restricted to ID facts. OOD recipients and donor paths analogously use only OOD facts. Different-bridge paths must change the target and their complete queries must be untrained. Same-bridge paths may be trained; their split is saved for separate scoring. Rows without donors remain present with explicit masks and reasons. """ if split not in SPLITS: raise ValueError(f"split must be one of {SPLITS}") rows = world[split] n, hops = len(rows), rows.shape[1] - 2 if not 2 <= hops <= 4: raise ValueError("Interventions require two-, three- or four-hop rows") atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" graph = { (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) for h, r, t in world[atomic_split] } by_relation = defaultdict(list) for (head, relation), (tail, _) in graph.items(): by_relation[relation].append((head, relation, tail)) training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} result = { "split": np.asarray(split), "atomic_split": np.asarray(atomic_split), "original_rows": rows.copy(), "original_bridge": np.full(n, -1, dtype=np.int64), "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), } for family in ("different", "same"): result.update( { family + "_donor": np.full((n, 3), -1, dtype=np.int64), family + "_counterfactual_rows": np.full_like(rows, -1), family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), family + "_valid": np.zeros(n, dtype=bool), family + "_candidate_count": np.zeros(n, dtype=np.int64), family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), } ) reasons = ( "same_head", "same_bridge", "missing_successor", "same_target", "head_is_answer", "trained_counterfactual", ) for reason in reasons: result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) for i, row in enumerate(rows): head, r1, target = int(row[0]), int(row[1]), int(row[-1]) original = _path(head, row[1:-1], graph) if original is None or original[0] != target: raise ValueError(f"Recipient is not a true all-{atomic_split} path") bridge = graph[head, r1][0] result["original_bridge"][i] = bridge result["original_atomic_indices"][i] = original[1] candidates = {"different": [], "same": []} for dh, dr, db in by_relation[r1]: continuation = _path(dh, row[1:-1], graph) if continuation is None: reason = "missing_successor" else: dt, edges = continuation query = (dh, *map(int, row[1:-1])) if dh != head and db == bridge and dh != target: candidates["same"].append((dh, dr, db, dt, edges)) reason = ( "same_head" if dh == head else "same_bridge" if db == bridge else "same_target" if dt == target else "head_is_answer" if dh in (target, dt) else "trained_counterfactual" if query in training else None ) if reason is None: candidates["different"].append((dh, dr, db, dt, edges)) if reason: result["different_rejected_" + reason][i] += 1 for family in ("different", "same"): choices = candidates[family] result[family + "_candidate_count"][i] = len(choices) donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) if donor is None: continue dh, dr, db, dt, edges = donor cf = (dh, *map(int, row[1:-1]), dt) result[family + "_donor"][i] = dh, dr, db result[family + "_counterfactual_rows"][i] = cf result[family + "_atomic_indices"][i] = edges result[family + "_valid"][i] = True result[family + "_reason"][i] = "eligible" result[family + "_counterfactual_split"][i] = ( "ood" if split == "ood_composite" else "train" if cf[:-1] in training else "reserved_test" if cf[:-1] in reserved else "unused" ) return result
def executed_blocks(model): return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks)
@torch.no_grad()def traced_forward( model, tokens, positions=None, *, patch_layer=None, component="both", donor_trace=None, identity=False, return_trace=False,): """Run eval forward, optionally mixing one executed layer's r1 state.
Trace fields contain only position r1, with shape [batch, width]. For a component patch the output is (recipient input + mixed A) + mixed M. Full replacement also changes the incoming residual, so it equals replacing A and M only at execution layer zero for same-r1 donors, not at later layers. """ if model.training: raise ValueError("Interventions require model.eval()") blocks = executed_blocks(model) if component not in COMPONENTS: raise ValueError(f"component must be one of {COMPONENTS}") if patch_layer is not None and ( isinstance(patch_layer, bool) or not isinstance(patch_layer, Integral) or not 0 <= patch_layer < len(blocks) ): raise ValueError("patch_layer must index an executed block") if identity and donor_trace is not None: raise ValueError("Identity and donor patches are mutually exclusive") if (donor_trace is not None or identity) != (patch_layer is not None): raise ValueError("A patch layer requires exactly one donor or identity patch") if donor_trace is not None and len(donor_trace) != len(blocks): raise ValueError("Donor trace must cover every executed layer") if tokens.shape[1] < 2: raise ValueError("The r1 position requires at least two tokens") x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) trace = [] for layer, block in enumerate(blocks): z = block.ln1(x) batch, length, width = z.shape attention = block.attention q, k, v = ( attention.qkv(z) .view(batch, length, 3, attention.heads, width // attention.heads) .unbind(2) ) a = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0, ) a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) m = block.mlp(block.ln2(x + a)) residual = (x + a) + m current = { "input": x[:, 1].clone(), "attention": a[:, 1].clone(), "mlp": m[:, 1].clone(), "residual": residual[:, 1].clone(), } if return_trace: trace.append(current) if layer == patch_layer: donor = current if identity else donor_trace[layer] if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): raise ValueError("Donor trace has incompatible batch or width") if component == "full": replacement = donor["residual"] else: mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] replacement = (x[:, 1] + mixed_a) + mixed_m residual = residual.clone() residual[:, 1] = replacement x = residual x = model.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] logits = F.linear(x, model.token.weight) return (logits, trace) if return_trace else logits
@torch.no_grad()def prefix_trace(model, prefixes, padded_length): """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) tokens[:, :2] = prefixes positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) return traced_forward(model, tokens, positions, return_trace=True)[1]
@torch.no_grad()def evaluate_condition( model, rows, device, padded_length, *, donor_prefixes=None, patch_layer=None, component="both", identity=False, batch_size=1024, verify_trace=False,): """Generate answer then EOS, reapplying exactly the same donor intervention.""" if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): raise ValueError("Donor prefixes must align one-to-one with recipient rows") answers, stops, logits_saved = [], [], [] max_delta = prefix_delta = 0.0 packed = pack_rows(rows, padded_length) for start in range(0, len(rows), batch_size): x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) x = x.clone() donor = None if donor_prefixes is not None: prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) donor = prefix_trace(model, prefixes, padded_length) arguments = dict( patch_layer=patch_layer, component=component, donor_trace=donor, identity=identity, ) logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) if verify_trace: if patch_layer is not None: raise ValueError("Native-forward verification applies to baseline only") reference = model(x, pos) max_delta = max(max_delta, float((reference - logits).abs().max())) if not torch.equal(reference.argmax(-1), logits.argmax(-1)): raise AssertionError("Traced forward changes native argmax") prefix = prefix_trace(model, x[:, :2], padded_length) for full, truncated in zip(trace, prefix, strict=True): for field in TRACE_FIELDS: prefix_delta = max( prefix_delta, float((full[field] - truncated[field]).abs().max()) ) answer = logits[:, 0].argmax(-1) logits_saved.append(logits[:, 0].cpu().numpy()) x[torch.arange(len(x), device=device), pos[:, 1]] = answer continuation = traced_forward(model, x, pos, **arguments) if verify_trace: reference = model(x, pos) max_delta = max(max_delta, float((reference - continuation).abs().max())) if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): raise AssertionError("Generated-answer trace changes native argmax") answers.append(answer.cpu().numpy()) stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) if max_delta > 1e-5 or prefix_delta > 1e-5: raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") return { "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), "answer_logits": np.concatenate(logits_saved) if logits_saved else np.empty((0, model.token.num_embeddings), dtype=np.float32), }, { "native_comparison_performed": verify_trace, "native_max_logit_delta": max_delta, "prefix_only_vs_full_all_layers_max_delta": prefix_delta, }
def _metrics(arrays, condition, selected, original, target, baseline): mask = selected & arrays[condition + "_valid"] n, total = int(mask.sum()), len(mask) answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"]
def mean(value): return float(value[mask].mean()) if n else None
return { "n": n, "total_n": total, "coverage": n / total if total else None, "target_answer_accuracy": mean(answer == target), "target_complete_accuracy": mean((answer == target) & (stop == 1)), "original_answer_accuracy": mean(answer == original), "original_complete_accuracy": mean((answer == original) & (stop == 1)), "other_answer_rate": mean((answer != target) & (answer != original)), "eos_accuracy": mean(stop == 1), "answer_change_rate": mean(answer != baseline), }
def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): """Evaluate every executed layer, preserving all rows and prerequisite masks.""" started = time.perf_counter() model.eval() split = str(donors["split"].item()) rows = world[split] if not np.array_equal(rows, donors["original_rows"]): raise ValueError("Donor rows differ from the registered evaluation split") n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 arrays = {key: value.copy() for key, value in donors.items()} all_rows = np.ones(n, dtype=bool) conditions, audits = {}, {}
def evaluate(name, mask, inputs, *, family=None, **kwargs): result, audit = evaluate_condition( model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs ) for key in ("answer", "stop"): values = np.full(n, -1, dtype=np.int64) values[mask] = result[key] arrays[name + "_" + key] = values arrays[name + "_valid"] = mask.copy() targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): values = np.full(n, np.nan, dtype=np.float32) values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] arrays[name + "_" + suffix] = values conditions[name] = { "family": family, **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, } audits[name] = audit
evaluate("baseline", all_rows, rows, verify_trace=True) for family in ("different", "same"): valid = donors[family + "_valid"] # Match batch shape as well as sequence shape for floating-point controls. evaluate(family + "_matched_baseline", valid, rows, family=family) evaluate( family + "_counterfactual_input", valid, donors[family + "_counterfactual_rows"], family=family, ) blocks = executed_blocks(model) for layer in range(len(blocks)): for component in COMPONENTS: identity_name = f"e{layer:03d}_identity_{component}" evaluate( identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True ) for key in ("answer", "stop", "original_logit", "target_logit"): if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): raise AssertionError(f"Identity patch changes {identity_name}.{key}") for family in ("different", "same"): valid = donors[family + "_valid"] name = f"e{layer:03d}_{family}_{component}" evaluate( name, valid, rows, family=family, patch_layer=layer, component=component, donor_prefixes=donors[family + "_donor"][valid, :2], ) if layer == len(blocks) - 1: for key in ("answer", "stop", "original_logit"): if not np.array_equal( arrays[name + "_" + key][valid], arrays[family + "_matched_baseline_" + key][valid], ): raise AssertionError("Last-block r1 patch changes later answer/EOS") if layer == 0: for family in ("different", "same"): valid = donors[family + "_valid"] for key in ("answer", "stop", "original_logit", "target_logit"): left = arrays[f"e000_{family}_both_{key}"][valid] right = arrays[f"e000_{family}_full_{key}"][valid] if not np.array_equal(left, right): raise AssertionError("First-layer same-r1 both/full differ") atomics, _ = evaluate_condition( model, world["atomic"], device, padded_length, batch_size=batch_size ) atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) arrays["atomic_rows"] = world["atomic"].copy() arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] groups = {"all_rows": all_rows} prerequisites = {} for family in ("original", "different", "same"): valid = all_rows if family == "original" else donors[family + "_valid"] indices = donors[family + "_atomic_indices"] correct = np.zeros_like(indices, dtype=bool) correct[valid] = atom_correct[indices[valid]] arrays[family + "_atomic_complete_correct"] = correct complete = valid & correct.all(axis=1) groups[family + "_all_atomic_correct"] = complete prerequisites[family] = { "n": int(valid.sum()), "total_n": n, "coverage": float(valid.mean()) if n else None, "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() if valid.any() else None, } for family in ("different", "same"): valid = donors[family + "_valid"] baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( arrays[family + "_matched_baseline_stop"] == 1 ) groups[family + "_donor_available"] = valid groups[family + "_donor_missing"] = ~valid cf = family + "_counterfactual_input" cf_correct = valid & ( arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] ) cf_correct &= arrays[cf + "_stop"] == 1 groups[family + "_native_original_and_counterfactual_correct"] = ( baseline_correct & cf_correct ) for category in ("train", "reserved_test", "unused", "ood"): groups[family + "_counterfactual_" + category] = valid & ( donors[family + "_counterfactual_split"] == category ) scores = {} for group, mask in groups.items(): arrays["subset_" + group] = mask.copy() scored = {} for condition, description in conditions.items(): family = description["family"] target = ( rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] ) scored[condition] = _metrics( arrays, condition, mask, rows[:, -1], target, arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], ) scores[group] = { "n": int(mask.sum()), "total_n": n, "coverage": float(mask.mean()) if n else None, "conditions": scored, } return { "split": split, "atomic_split": str(donors["atomic_split"].item()), "sample_rule": "training-independent fixed probe" if split == "test_composite" else "full split", "hops": padded_length - 2, "executed_depth": len(blocks), "unique_layers": len(model.blocks), "repeats": getattr(model, "repeats", 1), "patch_position": 1, "conditions": conditions, "scores": scores, "atomic_preconditions": prerequisites, "donor_coverage": { family: { "n": int(donors[family + "_valid"].sum()), "total_n": n, "reasons": dict(Counter(donors[family + "_reason"].tolist())), "counterfactual_split": dict( Counter(donors[family + "_counterfactual_split"].tolist()) ), } for family in ("different", "same") }, "engineering_checks": { "native_trace": audits["baseline"], "identity_all_layers_components": True, "first_layer_same_r1_both_equals_full": True, "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, "donor_nonpadding_tokens": 2, "donor_padded_length": padded_length, "mlp_recomputed_after_mixing": False, "eos_uses_generated_answer_and_reapplies_same_patch": True, }, "interpretation": ( "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " "Component mixtures retain recipient incoming residual. Both/full are equivalent " "only at first execution layer with same r1; later differences are expected. " "Facts and queries within one world are not independent experimental worlds." ), "evaluation_seconds": time.perf_counter() - started, }, arrays123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Depth-shared GPT blocks for controlled composition-learning comparisons.
This keeps the existing SmallGPT tokenization, causal attention, dropout and tiedreadout. ``config.layers`` counts independently parameterized blocks; each loopexecutes this whole block group. Positions and token embeddings are added once."""
from __future__ import annotations
import mathfrom dataclasses import replacefrom numbers import Integral
import torchfrom torch.nn import functional as F
from .bios_model import matmul_flopsfrom .grok_depth import SmallGPT
INITIALIZATIONS = frozenset({"legacy_unique", "scaled_effective", "zero_residual"})
def _positive_integer(value, name): if isinstance(value, bool) or not isinstance(value, Integral) or value < 1: raise ValueError(f"{name} must be a positive integer, got {value!r}") return int(value)
class LoopGPT(SmallGPT): """Vanilla fixed-loop Transformer with shared attention, MLP and block norms.
``legacy_unique`` reproduces SmallGPT's residual initialization based on the number of unique blocks. ``scaled_effective`` scales residual output weights by the total executed depth; ``zero_residual`` instead zeros those weights. Embeddings, other projections and all biases retain SmallGPT initialization.
Changing ``repeats`` in forward does not change parameter initialization. It is a computation-depth intervention, not an independently initialized model. Save repeats, dropout and initialization alongside ``config_dict()`` and the state dict when constructing checkpoints; they are architectural metadata. """
def __init__(self, config, repeats=1, dropout=0.1, initialization="scaled_effective"): repeats = _positive_integer(repeats, "repeats") _positive_integer(config.layers, "config.layers") if initialization not in INITIALIZATIONS: raise ValueError(f"initialization must be one of {sorted(INITIALIZATIONS)}") super().__init__(config, dropout=dropout) self.repeats = repeats self.initialization = initialization with torch.no_grad(): for block in self.blocks: for module in (block.attention.proj, block.mlp.down): if initialization == "scaled_effective": module.weight.div_(math.sqrt(repeats)) elif initialization == "zero_residual": module.weight.zero_()
@property def effective_depth(self): return self.config.layers * self.repeats
def iter_blocks(self, repeats=None): """Yield executed blocks; repeated occurrences are the same module object.""" count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") for _ in range(count): yield from self.blocks
def forward(self, tokens, positions=None, repeats=None): p = self.dropout if self.training else 0.0 x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) x = F.dropout(x, p=p, training=self.training) for block in self.iter_blocks(repeats): z = block.ln1(x) batch, length, width = z.shape a = block.attention q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) y = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=p, ) y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + F.dropout(y, p=p, training=self.training) x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) x = self.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] return F.linear(x, self.token.weight)
def flops(config, repeats, batch, sequence, output_positions=2, backward=True): """Estimate matmul FLOPs using executed blocks, counting the readout once.
Uses the same executed-shape estimate as bios_model.matmul_flops. Excludes elementwise operations and uses three forward equivalents for training. """ count = _positive_integer(repeats, "repeats") layers = _positive_integer(config.layers, "config.layers") return matmul_flops( replace(config, layers=layers * count), batch, sequence, output_positions=output_positions, backward=backward, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Graph-only, exposure-matched same-bridge donors for two-hop OOD queries.
Every donor contains only [head, r1]; its bridge is saved as truth, never fedto the model. ID donors must have actually occurred at the first position ofcomposite training. OOD donors have zero composite exposure at either position.All eligible donors and ID x OOD pairs are retained. A pair is a repeatedmeasurement of its recipient, not an independent query or world."""
from __future__ import annotations
import hashlibimport jsonfrom collections import defaultdictfrom collections.abc import Mappingfrom numbers import Integral
import numpy as np
from .grok_multihop_data import audit_world, path_details
def _nonnegative_integer(value, name): if isinstance(value, bool) or not isinstance(value, Integral) or value < 0: raise ValueError(f"{name} must be a nonnegative integer") return int(value)
def _exposure_spec(world, run_metadata, steps): spec = run_metadata.get("spec", run_metadata) if not isinstance(spec, Mapping): raise ValueError("Run metadata must contain a specification mapping") count = _nonnegative_integer(spec["steps"] if steps is None else steps, "steps") if count > _nonnegative_integer(spec["steps"], "registered steps"): raise ValueError("Exposure cannot exceed the registered training endpoint") batch = _nonnegative_integer(spec["batch_size"], "batch_size") atomic_batch = _nonnegative_integer(spec["n_atomic_per_batch"], "n_atomic_per_batch") seed = _nonnegative_integer(spec["stream_seed"], "stream_seed") if batch < 1 or atomic_batch > batch: raise ValueError("Require batch_size > 0 and n_atomic_per_batch <= batch_size") for key in ("world_seed", "hops"): expected = world["metadata"]["seed" if key == "world_seed" else key] if key in spec and spec[key] != expected: raise ValueError(f"Run specification disagrees with the world: {key}") return { "dataset_sha256": world["metadata"]["dataset_sha256"], "stream_seed": seed, "steps": count, "batch_size": batch, "n_atomic_per_batch": atomic_batch, "atomic_size": len(world["atomic"]), "composite_size": len(world["train_composite"]), "stream": "StratifiedStream independent shuffled epochs v1", }
def _cache_key(spec): return hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest()
def _record_exposures(size, draws, seed, tag): """Replay the final partial epoch without materializing the full sample stream.""" if not size: if draws: raise ValueError("A sampled training stratum cannot be empty") return np.empty(0, dtype=np.int64) complete, remainder = divmod(draws, size) counts = np.full(size, complete, dtype=np.int64) if remainder: rng = np.random.default_rng(np.random.SeedSequence([seed, tag])) for _ in range(complete): rng.permutation(size) counts[rng.permutation(size)[:remainder]] += 1 return counts
def actual_exposure_counts(world, run_metadata, *, steps=None): """Count actual atomic and composite records sampled through a fixed step.
The training sampler has independent atomic/composite RNG streams, so its interleaving draws do not change these counts. Full epochs expose every record once; only the final partial epoch needs its exact permutation. ``cache_key`` depends on data, sample-stream seed, step and batch mixture, but not architecture or initialization, which do not change this sampler. """ checked = audit_world(world) if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): raise ValueError("World metadata hash does not match the data") if world["metadata"]["hops"] != 2: raise ValueError("Same-bridge exposure comparison requires two-hop worlds") spec = _exposure_spec(world, run_metadata, steps) atom_count = _record_exposures( spec["atomic_size"], spec["steps"] * spec["n_atomic_per_batch"], spec["stream_seed"], 145101, ) composite_count = _record_exposures( spec["composite_size"], spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]), spec["stream_seed"], 145102, ) _, edges = path_details( world["train_composite"], world["atomic"], world["metadata"]["entities"], world["metadata"]["relations"], ) table = np.zeros((len(world["atomic"]), 2), dtype=np.int64) actual = np.zeros_like(table) for position in range(2): np.add.at(table[:, position], edges[:, position], 1) np.add.at(actual[:, position], edges[:, position], composite_count) return { "cache_key": _cache_key(spec), "cache_spec": spec, "atomic_record_counts": atom_count, "composite_record_counts": composite_count, "table_position_counts": table, "actual_position_counts": actual, }
def _rows(values, columns): return np.asarray(values, dtype=np.int64).reshape(-1, columns)
def select_same_bridge_donors(world, run_metadata, *, steps=None, exposure=None): """Enumerate same-r1/same-bridge ID and OOD donors without model selection.
Inputs are a standard audited loop world and either run metadata with a ``spec`` field or the specification directly. All original OOD rows stay aligned with validity masks and explicit reasons. Flattened donor arrays include recipients with only one donor class. Main pairs require both. ``exposure`` may cache ``actual_exposure_counts`` for a shared sample stream.
For pair-level scores, first average pairs within each recipient (using pair_weights), then average recipients. Pair weights sum to one for each common recipient; they do not sum to one across the whole world. """ checked = audit_world(world) if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): raise ValueError("World metadata hash does not match the data") if world["metadata"]["hops"] != 2: raise ValueError("Same-bridge selection requires two-hop worlds") spec = _exposure_spec(world, run_metadata, steps) exposure = ( actual_exposure_counts(world, run_metadata, steps=steps) if exposure is None else exposure ) if exposure.get("cache_key") != _cache_key(spec) or exposure.get("cache_spec") != spec: raise ValueError("Cached exposure belongs to another world or sample stream") atoms = world["atomic"] position_counts = np.asarray(exposure["actual_position_counts"]) table_counts = np.asarray(exposure["table_position_counts"]) if ( position_counts.shape != (len(atoms), 2) or table_counts.shape != position_counts.shape or position_counts.dtype != np.int64 or table_counts.dtype != np.int64 or (position_counts < 0).any() or (table_counts < 0).any() ): raise ValueError("Cached position exposure counts have invalid shape or values") atom_index = {tuple(map(int, row)): i for i, row in enumerate(atoms)} is_id = np.zeros(len(atoms), dtype=bool) is_id[[atom_index[tuple(map(int, row))] for row in world["id_atomic"]]] = True if position_counts[~is_id].any() or table_counts[~is_id].any(): raise ValueError("An OOD fact has composite training exposure") expected_draws = spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]) if not np.array_equal(position_counts.sum(axis=0), [expected_draws, expected_draws]): raise ValueError("Cached position counts disagree with the registered sample budget") incoming = defaultdict(list) for i, (head, relation, bridge) in enumerate(atoms): incoming[int(relation), int(bridge)].append((int(head), i)) for candidates in incoming.values(): candidates.sort() original = world["ood_composite"] nodes, edges = path_details( original, atoms, world["metadata"]["entities"], world["metadata"]["relations"] ) if is_id[edges].any(): raise ValueError("Recipients must contain only OOD facts") n = len(original) id_indices, ood_indices = [], [] id_recipient, ood_recipient = [], [] id_offsets, ood_offsets = [0], [0] second_only = np.zeros(n, dtype=np.int64) nominal_unexposed = np.zeros(n, dtype=np.int64) rejected_same_head = np.zeros(n, dtype=np.int64) rejected_answer_head = np.zeros(n, dtype=np.int64) for i, (head, r1, _r2, target) in enumerate(original): for donor_head, fact in incoming[int(r1), int(nodes[i, 1])]: if donor_head == head: rejected_same_head[i] += 1 continue if donor_head == target: rejected_answer_head[i] += 1 continue if is_id[fact]: if position_counts[fact, 0] > 0: id_indices.append(fact) id_recipient.append(i) elif position_counts[fact, 1] > 0: second_only[i] += 1 else: nominal_unexposed[i] += 1 else: ood_indices.append(fact) ood_recipient.append(i) id_offsets.append(len(id_indices)) ood_offsets.append(len(ood_indices)) id_offsets = np.asarray(id_offsets, dtype=np.int64) ood_offsets = np.asarray(ood_offsets, dtype=np.int64) id_count, ood_count = np.diff(id_offsets), np.diff(ood_offsets) valid = (id_count > 0) & (ood_count > 0) pair_recipient, pair_id, pair_ood, weights = [], [], [], [] for i in np.flatnonzero(valid): weight = 1.0 / int(id_count[i] * ood_count[i]) for j in range(id_offsets[i], id_offsets[i + 1]): for k in range(ood_offsets[i], ood_offsets[i + 1]): pair_recipient.append(i) pair_id.append(j) pair_ood.append(k) weights.append(weight) pair_recipient = np.asarray(pair_recipient, dtype=np.int64) pair_id = np.asarray(pair_id, dtype=np.int64) pair_ood = np.asarray(pair_ood, dtype=np.int64) id_indices = np.asarray(id_indices, dtype=np.int64) ood_indices = np.asarray(ood_indices, dtype=np.int64) reason = np.full(n, "eligible", dtype="U40") reason[(id_count == 0) & (ood_count > 0)] = "no_id_first_position_donor" reason[(id_count > 0) & (ood_count == 0)] = "no_other_ood_donor" reason[(id_count == 0) & (ood_count == 0)] = "no_id_or_other_ood_donor" result = { "original_rows": original.copy(), "original_bridge": nodes[:, 1].copy(), "original_atomic_indices": edges.copy(), "original_prefix_contains_answer": original[:, 0] == original[:, -1], "original_answer_equals_bridge": nodes[:, 1] == original[:, -1], "common_valid": valid, "reason": reason, "id_candidate_count": id_count, "ood_candidate_count": ood_count, "id_second_only_candidate_count": second_only, "id_unexposed_candidate_count": nominal_unexposed, "rejected_same_head_count": rejected_same_head, "rejected_answer_head_count": rejected_answer_head, "id_candidate_offsets": id_offsets, "ood_candidate_offsets": ood_offsets, "id_donor_atomic_indices": id_indices, "ood_donor_atomic_indices": ood_indices, "id_donor_rows": atoms[id_indices].copy(), "ood_donor_rows": atoms[ood_indices].copy(), "id_recipient_indices": np.asarray(id_recipient, dtype=np.int64), "ood_recipient_indices": np.asarray(ood_recipient, dtype=np.int64), "pair_recipient_indices": pair_recipient, "pair_rows": original[pair_recipient].copy(), "pair_id_indices": pair_id, "pair_ood_indices": pair_ood, "pair_weights": np.asarray(weights, dtype=np.float64), "pair_id_donor_rows": atoms[id_indices[pair_id]].copy(), "pair_ood_donor_rows": atoms[ood_indices[pair_ood]].copy(), "pair_self_donor_rows": atoms[edges[pair_recipient, 0]].copy(), "atomic_is_id": is_id, "atomic_single_training_exposure": np.asarray(exposure["atomic_record_counts"]).copy(), "atomic_composite_table_position_counts": table_counts.copy(), "atomic_composite_actual_position_exposure": position_counts.copy(), "composite_record_training_exposure": np.asarray( exposure["composite_record_counts"] ).copy(), } trained = {tuple(map(int, row[:-1])) for row in world["train_composite"]} for family in ("id", "ood"): cf = result["pair_rows"].copy() cf[:, 0] = result["pair_" + family + "_donor_rows"][:, 0] _, cf_edges = path_details( cf, atoms, world["metadata"]["entities"], world["metadata"]["relations"] ) if any(tuple(map(int, row[:-1])) in trained for row in cf): raise ValueError("A same-bridge counterfactual query was used in training") if is_id[cf_edges[:, 1]].any(): raise ValueError("A donor has changed the recipient's OOD successor") result["pair_" + family + "_counterfactual_rows"] = cf result["pair_" + family + "_counterfactual_atomic_indices"] = cf_edges result["pair_" + family + "_counterfactual_split"] = np.full( len(cf), "mixed_id_ood" if family == "id" else "pure_ood", dtype="U16" ) result["audit"] = { "dataset_sha256": checked["dataset_sha256"], "exposure_cache_key": exposure["cache_key"], "exposure_cache_spec": spec, "recipient_split": "ood_composite", "selection": "enumerate all graph-qualified ID x OOD pairs; no model-based selection", "id_requirement": "same r1/bridge, different head, actual first-position exposure > 0", "ood_requirement": ( "same r1/bridge, different head, no composite exposure at either position" ), "answer_head_excluded": True, "prefix_inputs": "donor_rows[:, :2]; bridge is audit truth, never model input", "successor": "unchanged OOD second fact for both donor classes", "all_recipient_n": n, "id_available_n": int((id_count > 0).sum()), "ood_available_n": int((ood_count > 0).sum()), "common_n": int(valid.sum()), "common_fraction": float(valid.mean()) if n else None, "pair_n": len(pair_recipient), "unique_original_first_facts_n": len(np.unique(edges[:, 0])), "unique_original_second_facts_n": len(np.unique(edges[:, 1])), "unique_common_first_facts_n": len(np.unique(edges[valid, 0])), "unique_common_second_facts_n": len(np.unique(edges[valid, 1])), "unique_common_id_donor_facts_n": len(np.unique(id_indices[pair_id])), "unique_common_ood_donor_facts_n": len(np.unique(ood_indices[pair_ood])), "unique_all_id_donor_facts_n": len(np.unique(id_indices)), "unique_all_ood_donor_facts_n": len(np.unique(ood_indices)), "unique_common_r1_bridge_groups_n": len( np.unique(np.c_[original[valid, 1], nodes[valid, 1]], axis=0) ), "original_prefix_contains_answer_n": int(result["original_prefix_contains_answer"].sum()), "common_prefix_contains_answer_n": int( result["original_prefix_contains_answer"][valid].sum() ), "original_answer_equals_bridge_n": int(result["original_answer_equals_bridge"].sum()), "common_answer_equals_bridge_n": int(result["original_answer_equals_bridge"][valid].sum()), "common_first_edge_self_loop_n": int((original[valid, 0] == nodes[valid, 1]).sum()), "common_id_donor_prefix_contains_answer_n": int( (result["pair_id_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() ), "common_ood_donor_prefix_contains_answer_n": int( (result["pair_ood_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() ), "id_second_only_candidate_n": int(second_only.sum()), "id_unexposed_candidate_n": int(nominal_unexposed.sum()), "missing_reasons": { str(value): int((reason == value).sum()) for value in np.unique(reason) }, "aggregation": ( "mean pairs per recipient, recipients per model, " "initializations per world, worlds equally" ), } return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353"""Same-bridge prefix interventions, with query-balanced donor summaries.
The donor selector never sees model scores. This evaluator reuses the auditedfirst-block component mixer; it does not retrain models or recompute the currentMLP after mixing. All candidate donors are evaluated, then averaged within therecipient query before any world-level aggregation."""
from __future__ import annotations
import hashlibimport time
import numpy as npimport torch
from .grok_loop_mechanism import COMPONENTS, evaluate_condition, executed_blocks
METRICS = ( "answer_accuracy", "complete_accuracy", "eos_accuracy", "target_probability", "target_log_probability", "target_margin",)
def state_digest(model): digest = hashlib.sha256() for name, tensor in sorted(model.state_dict().items()): digest.update(name.encode()) value = tensor.detach().cpu().contiguous().numpy() digest.update(str(value.dtype).encode()) digest.update(str(value.shape).encode()) digest.update(value.tobytes()) return digest.hexdigest()
def prediction_metrics(prediction, targets): targets = np.asarray(targets, dtype=np.int64) logits = np.asarray(prediction["answer_logits"], dtype=np.float64) answer, stop = prediction["answer"], prediction["stop"] if logits.ndim != 2 or logits.shape[0] != len(targets): raise ValueError("Logits and targets must align") if answer.shape != targets.shape or stop.shape != targets.shape: raise ValueError("Generated answers and EOS must align with targets") if not np.isfinite(logits).all(): raise ValueError("Nonfinite answer logits") if len(targets) and (targets.min() < 0 or targets.max() >= logits.shape[1]): raise ValueError("Target outside vocabulary") maximum = logits.max(axis=1) if len(targets) else np.empty(0) partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(axis=1)) target_logits = logits[np.arange(len(targets)), targets] competitors = logits.copy() competitors[np.arange(len(targets)), targets] = -np.inf log_probability = target_logits - partition return { "answer_accuracy": (answer == targets).astype(np.float64), "complete_accuracy": ((answer == targets) & (stop == 1)).astype(np.float64), "eos_accuracy": (stop == 1).astype(np.float64), "target_probability": np.exp(log_probability), "target_log_probability": log_probability, "target_margin": target_logits - competitors.max(axis=1), }
def query_mean(values, recipient_indices, n_recipients): """Missing recipients remain NaN; repeated donors never add query weight.""" values = np.asarray(values, dtype=np.float64) indices = np.asarray(recipient_indices, dtype=np.int64) if values.shape != indices.shape or not np.isfinite(values).all(): raise ValueError("Finite, aligned one-dimensional donor values are required") if len(indices) and (indices.min() < 0 or indices.max() >= n_recipients): raise ValueError("Recipient index outside query pool") count = np.bincount(indices, minlength=n_recipients) sums = np.bincount(indices, weights=values, minlength=n_recipients) result = np.full(n_recipients, np.nan) np.divide(sums, count, out=result, where=count > 0) return result
def summarize(values, recipient_indices, selected, n_recipients): selected = np.asarray(selected, dtype=bool) if selected.shape != (n_recipients,): raise ValueError("Selection must align with the complete recipient pool") indices = np.asarray(recipient_indices, dtype=np.int64) n = int(selected.sum()) metrics = {} available = np.zeros(n_recipients, dtype=bool) available[indices] = True mask = selected & available for name in METRICS: balanced = query_mean(values[name], indices, n_recipients) metrics[name] = float(balanced[mask].mean()) if mask.any() else None return { "n_recipients": int(mask.sum()), "selected_recipients": n, "total_recipients": n_recipients, "coverage": float(mask.mean()) if n_recipients else None, "n_donor_evaluations": int(selected[indices].sum()), **metrics, }
def _equal_predictions(left, right, label): for name in ("answer", "stop", "answer_logits"): if not np.array_equal(left[name], right[name]): raise AssertionError(f"{label}: {name} differs")
def _fixed_batch_evaluate(model, inputs, device, physical_batch, **kwargs): """Keep GPU matrix shapes equal to the full historical recipient batch.
Duplicate padding rows exist only to fill the physical batch and are discarded before scoring or saving. No PAD row is treated as a donor. """ if not len(inputs): return evaluate_condition(model, inputs, device, 4, batch_size=physical_batch, **kwargs) prefixes = kwargs.pop("donor_prefixes", None) outputs = [] audits = [] for start in range(0, len(inputs), physical_batch): actual = min(physical_batch, len(inputs) - start) block = inputs[start : start + actual] padded = np.concatenate([block, np.repeat(block[-1:], physical_batch - actual, axis=0)]) arguments = dict(kwargs) if prefixes is not None: prefix = prefixes[start : start + actual] arguments["donor_prefixes"] = np.concatenate( [prefix, np.repeat(prefix[-1:], physical_batch - actual, axis=0)] ) prediction, audit = evaluate_condition( model, padded, device, 4, batch_size=physical_batch, **arguments ) outputs.append({field: value[:actual] for field, value in prediction.items()}) audits.append(audit) return {field: np.concatenate([row[field] for row in outputs]) for field in outputs[0]}, { "native_comparison_performed": all(row["native_comparison_performed"] for row in audits), "native_max_logit_delta": max(row["native_max_logit_delta"] for row in audits), "prefix_only_vs_full_all_layers_max_delta": max( row["prefix_only_vs_full_all_layers_max_delta"] for row in audits ), "physical_batch_size": physical_batch, "scored_evaluations": len(inputs), "discarded_duplicate_padding": len(outputs) * physical_batch - len(inputs), }
@torch.no_grad()def evaluate_same_bridge(model, world, donors, *, device="cuda:0", batch_size=1024): started = time.perf_counter() model.eval() before = state_digest(model) if any(parameter.requires_grad for parameter in model.parameters()): raise ValueError("All model parameters must be frozen") rows = donors["original_rows"] if not np.array_equal(rows, world["ood_composite"]) or rows.shape[1] != 4: raise ValueError("Expected the unchanged complete pure-OOD two-hop pool") n = len(rows) arrays = {k: v.copy() for k, v in donors.items() if isinstance(v, np.ndarray)} results, values, descriptions, engineering = {}, {}, {}, {}
def evaluate(name, inputs, indices, **kwargs): prediction, audit = _fixed_batch_evaluate( model, inputs, device, max(1, min(n, batch_size)), **kwargs ) indices = np.asarray(indices, dtype=np.int64) measured = prediction_metrics(prediction, inputs[:, -1]) for field, vector in {**prediction, **measured}.items(): arrays[name + "_" + field] = vector arrays[name + "_recipient_indices"] = indices results[name], values[name] = prediction, measured descriptions[name] = { "n_evaluations": len(inputs), "patch_layer": kwargs.get("patch_layer"), "component": kwargs.get("component"), "identity": kwargs.get("identity", False), "prefix_only": kwargs.get("donor_prefixes") is not None, } engineering[name] = audit return prediction
all_indices = np.arange(n, dtype=np.int64) baseline = evaluate("baseline", rows, all_indices, verify_trace=True) for component in COMPONENTS: self_result = evaluate( "self_" + component, rows, all_indices, patch_layer=0, component=component, identity=True, ) prefix_result = evaluate( "original_prefix_" + component, rows, all_indices, patch_layer=0, component=component, donor_prefixes=rows[:, :2], ) _equal_predictions(baseline, self_result, "self " + component) _equal_predictions(baseline, prefix_result, "original prefix " + component)
atomic_prediction, atomic_audit = evaluate_condition( model, world["atomic"], device, 4, batch_size=batch_size, verify_trace=True ) arrays["atomic_rows"] = world["atomic"].copy() for field, vector in atomic_prediction.items(): arrays["atomic_" + field] = vector atomic_complete = (atomic_prediction["answer"] == world["atomic"][:, -1]) & ( atomic_prediction["stop"] == 1 ) arrays["atomic_complete_correct"] = atomic_complete arrays["original_atomic_complete_correct"] = atomic_complete[donors["original_atomic_indices"]] engineering["atomic_native"] = atomic_audit atom_lookup = {tuple(map(int, r)): i for i, r in enumerate(world["atomic"])} for family in ("id", "ood"): indices = donors[family + "_recipient_indices"] inputs = rows[indices] donor_rows = donors[family + "_donor_rows"] prefixes = donor_rows[:, :2] counterfactual = inputs.copy() counterfactual[:, 0] = donor_rows[:, 0] atomic_indices = np.asarray( [atom_lookup[tuple(map(int, r))] for r in donor_rows], dtype=np.int64 ) arrays[family + "_donor_atomic_indices"] = atomic_indices arrays[family + "_donor_atomic_complete_correct"] = atomic_complete[atomic_indices] matched = evaluate(family + "_baseline", inputs, indices) _equal_predictions( {k: v[indices] for k, v in baseline.items()}, matched, family + " batch match" ) engineering[family + "_batch_shape_comparison"] = { "answers_and_eos_identical": True, "max_logit_delta": 0.0, "bitwise_equal_full_logits": True, "intervention_baseline_has_identical_batch_shape": True, } evaluate(family + "_counterfactual", counterfactual, indices) self_result = evaluate( family + "_self", inputs, indices, patch_layer=0, component="full", identity=True, ) _equal_predictions(matched, self_result, family + " self") for component in COMPONENTS: evaluate( family + "_" + component, inputs, indices, patch_layer=0, component=component, donor_prefixes=prefixes, ) if len(executed_blocks(model)) == 1: _equal_predictions(matched, results[family + "_" + component], "C1 inert patch") _equal_predictions( results[family + "_both"], results[family + "_full"], family + " both/full" )
common = donors["common_valid"] groups = { "all": np.ones(n, dtype=bool), "paired": common, "id_only": (donors["id_candidate_count"] > 0) & (donors["ood_candidate_count"] == 0), "ood_only": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] > 0), "neither": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] == 0), "paired_original_atomics_correct": common & arrays["original_atomic_complete_correct"].all(axis=1), "paired_baseline_failed": common & (values["baseline"]["complete_accuracy"] == 0), "paired_baseline_correct": common & (values["baseline"]["complete_accuracy"] == 1), } # Conditional diagnostics are reported alongside the unfiltered paired pool. pid, pod = donors["pair_id_indices"], donors["pair_ood_indices"] pair_indices = donors["pair_recipient_indices"] known_pair = arrays["original_atomic_complete_correct"][pair_indices].all(axis=1) known_pair &= arrays["id_donor_atomic_complete_correct"][pid] known_pair &= arrays["ood_donor_atomic_complete_correct"][pod] cf_pair = values["id_counterfactual"]["complete_accuracy"][pid].astype(bool) cf_pair &= values["ood_counterfactual"]["complete_accuracy"][pod].astype(bool) arrays["pair_all_atomics_correct"] = known_pair arrays["pair_both_counterfactual_correct"] = cf_pair # A query is included in the following conditional subset only if every # registered donor pair satisfies the prerequisite, avoiding donor picking. for name, flag in ( ("all_atomics_correct", known_pair), ("both_counterfactual_correct", cf_pair), ): average = query_mean(flag.astype(float), pair_indices, n) groups["paired_" + name] = common & (average == 1) for name, mask in groups.items(): arrays["subset_" + name] = mask
scores = {} for group, selected in groups.items(): scores[group] = { condition: summarize(measured, arrays[condition + "_recipient_indices"], selected, n) for condition, measured in values.items() } contrasts = {} for component in COMPONENTS: id_values, ood_values = values["id_" + component], values["ood_" + component] difference = { metric: id_values[metric][pid] - ood_values[metric][pod] for metric in METRICS } adjusted = { metric: (id_values[metric][pid] - values["id_baseline"][metric][pid]) - (ood_values[metric][pod] - values["ood_baseline"][metric][pod]) for metric in METRICS } for group, mask in groups.items(): contrasts[group + ":" + component] = { "id_minus_ood": summarize(difference, pair_indices, mask, n), "baseline_adjusted_id_minus_ood": summarize(adjusted, pair_indices, mask, n), } after = state_digest(model) if before != after: raise AssertionError("Interventions changed model parameters or buffers") return arrays, { "seconds": time.perf_counter() - started, "n_original_queries": n, "n_common_queries": int(common.sum()), "n_pairs": len(pair_indices), "conditions": descriptions, "scores": scores, "contrasts": contrasts, "engineering": { "native_and_prefix_checks": engineering, "all_self_and_original_prefix_conditions_equal_baseline": True, "both_equals_full_first_execution_layer": True, "c1_last_block_inert": len(executed_blocks(model)) == 1, "parameters_unchanged": True, "model_state_sha256_before": before, "model_state_sha256_after": after, "mlp_recomputed_after_mixing": False, "donor_nonpadding_tokens": 2, "patch_layer": 0, "patch_position": 1, "eos_uses_generated_answer": True, "training_updates": 0, "physical_condition_batch_size": max(1, min(n, batch_size)), "duplicate_padding_never_scored_or_saved": True, }, "statistical_unit": ( "mean over all donors within recipient; initialization within world; equal worlds" ), "selection": "graph and registered training exposures only; scores do not select donors", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349"""Paired continuation: terminal versus distributed answer supervision.
Historical model/trainer files remain unchanged. All heads branch off the sametrajectory; their LayerNorm outputs never replace the recurrent residual state."""
from __future__ import annotations
import hashlibimport jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfigfrom .grok_depth import GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_data import StratifiedStreamfrom .grok_loop_model import LoopGPT, flopsfrom .grok_multihop import pack_rows
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def tensor_digest(tensors): h = hashlib.sha256() for key, value in sorted(tensors.items()): h.update(key.encode()) h.update(value.detach().cpu().contiguous().numpy().tobytes()) return h.hexdigest()
class SupervisionGPT(LoopGPT): def states(self, tokens, repeats): """Yield full group-boundary states with exactly the native dropout order.""" p = self.dropout if self.training else 0.0 x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) x = F.dropout(x, p=p, training=self.training) for _ in range(repeats): for block in self.blocks: z = block.ln1(x) batch, length, width = z.shape a = block.attention q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) y = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=p, ) y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) x = x + F.dropout(y, p=p, training=self.training) x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) yield x
def readout(self, x, positions=None): x = self.ln_final(x) if positions is not None: x = x[torch.arange(len(x), device=x.device)[:, None], positions] return F.linear(x, self.token.weight)
def at_loops(self, tokens, positions, loops=(2, 3, 4)): if not loops or tuple(sorted(set(loops))) != tuple(loops) or loops[0] < 1: raise ValueError("Loop endpoints must be positive, unique, sorted") return tuple( self.readout(x, positions) for r, x in enumerate(self.states(tokens, max(loops)), 1) if r in loops )
def answer_losses(model, x, positions, labels): return torch.stack( [F.cross_entropy(z.flatten(0, 1), labels.flatten()) for z in model.at_loops(x, positions)] )
class SupervisionStep(GraphStep): """Both arms execute all three CE/backward branches, including zero weights."""
def __init__(self, model, optimizer, table, batch_size, arm): if arm not in ("single", "multi"): raise ValueError(arm) weights = [0.0, 0.0, 1.0] if arm == "single" else [1 / 3] * 3 self.weights = torch.tensor(weights, device=table[0].device) super().__init__(model, optimizer, table, batch_size)
def eager(self): self.optimizer.zero_grad(set_to_none=False) x, pos, labels = (t[self.index] for t in self.table) self.components = answer_losses(self.model, x, pos, labels) loss = (self.components * self.weights).sum() loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def from_state(state, device): spec = state["spec"] cfg = ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) model = SupervisionGPT( cfg, repeats=spec["repeats"], dropout=spec["dropout"], initialization=spec["init_scheme"], ).to(device) model.load_state_dict(state["model"]) return model
def score_predictions(pred): correct = pred["answer"] == pred["target"] return { "n": len(correct), "accuracy": float((correct & (pred["stop"] == 1)).mean()), "answer_accuracy": float(correct.mean()), "eos_accuracy": float((pred["stop"] == 1).mean()), "nll": float(pred["nll"].mean()), "answer_nll": float(pred["nll"][:, 0].mean()), "answer_probability": float(np.exp(-pred["nll"][:, 0].astype(float)).mean()), "margin": float(pred["margin"].mean()), }
@torch.no_grad()def evaluate(model, rows, device, repeats, batch_size=1024): was_training = model.training model.eval() packed = pack_rows(rows, 4) parts = [] for start in range(0, len(rows), batch_size): x, pos, labels = ( torch.as_tensor(a[start : start + batch_size], device=device) for a in packed ) x = x.clone() z = model(x, pos, repeats=repeats) nll = F.cross_entropy(z.flatten(0, 1), labels.flatten(), reduction="none").view(-1, 2) answer = z[:, 0].argmax(-1) x[torch.arange(len(x), device=device), pos[:, 1]] = answer eos = model(x, pos, repeats=repeats)[:, 1] target_score = z[:, 0].gather(1, labels[:, :1]).squeeze(1) alternatives = z[:, 0].clone() alternatives.scatter_(1, labels[:, :1], -torch.inf) parts.append( { "answer": answer.cpu().numpy(), "stop": eos.argmax(-1).cpu().numpy(), "target": labels[:, 0].cpu().numpy(), "nll": nll.cpu().numpy(), "margin": (target_score - alternatives.max(-1).values).cpu().numpy(), "logits": z.cpu().numpy(), "generated_eos_logits": eos.cpu().numpy(), } ) model.train(was_training) pred = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} return score_predictions(pred), pred
def load_world(source): with np.load(Path(source) / "world.npz", allow_pickle=False) as z: world = {k: z[k].copy() for k in z.files} world["metadata"] = json.loads((Path(source) / "world-metadata.json").read_text()) return world
def restore_rng(state, device): torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
def run(spec, out, device, resume=False): out, device = Path(out), torch.device(device) source = Path(spec["source"]) origin = torch.load(source / "latest.pt", map_location=device, weights_only=False) if origin["step"] != 128000 or origin["spec"]["hops"] != 2: raise ValueError("Expected completed historical two-hop checkpoint") world = load_world(source) current = ( torch.load(out / "latest.pt", map_location=device, weights_only=False) if resume else origin ) if resume and current["continuation"] != spec: raise ValueError("Resume contract changed") model = from_state(current, device) lr = torch.tensor(spec["lr"], device=device) opt = make_optimizer(model, lr, origin["spec"]["weight_decay"]) opt.load_state_dict(current["optimizer"]) lr = opt.param_groups[0]["lr"] for group in opt.param_groups: group["lr"] = lr lr.fill_(spec["lr"]) packed = [pack_rows(world[name], 4) for name in ("atomic", "train_composite")] table = tuple( torch.as_tensor(np.concatenate(a), device=device) for a in zip(*packed, strict=True) ) stream = StratifiedStream( len(world["atomic"]), len(world["train_composite"]), 256, 32, origin["spec"]["stream_seed"], ) stream.load_state_dict(current["stream"]) restore_rng(current, device) step = current["step"] if resume else 0 training_seconds = current.get("continuation_training_seconds", 0.0) if resume else 0.0 records = json.loads((out / "learning.json").read_text()) if resume else [] records = [r for r in records if r["step"] <= step] before_capture = tensor_digest(model.state_dict()) optimizer_before = { p: {k: v.clone() for k, v in s.items() if torch.is_tensor(v)} for p, s in opt.state.items() } model.train() graph = SupervisionStep(model, opt, table, 256, spec["arm"]) capture_ok = before_capture == tensor_digest(model.state_dict()) and all( torch.equal(v, opt.state[p][k]) for p, s in optimizer_before.items() for k, v in s.items() ) if not capture_ok: raise ValueError("CUDA capture altered source model/optimizer") del optimizer_before flop_step = flops(model.config, 4, 256, 4, output_positions=6) sampling_hash = hashlib.sha256() # Persist cumulative per-row exposure as well as stream state for paired audit. exposure = ( current["continuation_exposure"].cpu().numpy() if resume else np.zeros(len(table[0]), dtype=np.int64) )
def measure(at, components=None): rng = {"cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device)} row = { "step": at, "utc": utc(), "training_seconds": training_seconds, "estimated_training_matmul_flops": at * flop_step, "logical_examples": at * 256, "atomic_presentations": at * 32, "composite_presentations": at * 224, "weighted_target_tokens": at * 256 * 2, "executed_loss_target_tokens": at * 256 * 2 * 3, "last_batch_losses_2_3_4": components, "evaluations": {}, } repeats = spec["endpoint_repeats"] if at in (0, spec["steps"]) else [2, 3, 4, 8] preds = {} for name in ("atomic", "test_full_composite", "ood_composite", "train_composite"): counts = [2, 3, 4] if name == "train_composite" else repeats for r in counts: metric, pred = evaluate(model, world[name], device, r) key = f"{name}_r{r}" row["evaluations"][key] = metric preds.update({key + "_" + k: v for k, v in pred.items()}) if name == "atomic": for subset in ("id_atomic", "ood_atomic"): ids = {tuple(x) for x in world[subset]} mask = np.array([tuple(x) in ids for x in world["atomic"]]) row["evaluations"][f"{subset}_r{r}"] = score_predictions( {k: v[mask] for k, v in pred.items()} ) records.append(row) write_json(out / "learning.json", records) np.savez_compressed(out / f"predictions-{at:07d}.npz", **preds) restore_rng(rng, device) state = { "spec": origin["spec"], "continuation": spec, "step": at, "source_training_step": origin["step"], "model": model.state_dict(), "optimizer": opt.state_dict(), "stream": stream.state_dict(), "cpu_rng": rng["cpu_rng"], "cuda_rng": rng["cuda_rng"], "continuation_exposure": torch.as_tensor(exposure), "continuation_training_seconds": training_seconds, } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(out / "latest.pt") torch.save( {"spec": origin["spec"], "step": at, "model": model.state_dict()}, out / f"weights-{at:07d}.pt", ) ev = row["evaluations"] status = { "state": "complete" if at == spec["steps"] else "running", "step": at, "arm": spec["arm"], "ood_r4": ev["ood_composite_r4"]["accuracy"], "ood_r8": ev["ood_composite_r8"]["accuracy"], "atomic_r4": ev["atomic_r4"]["accuracy"], "id_r4": ev["test_full_composite_r4"]["accuracy"], "utc": utc(), } write_json(out / "status.json", status) print(json.dumps(status), flush=True) return row
if not resume: measure(0) for end in [n for n in spec["nodes"] if n > step]: model.train() torch.cuda.synchronize() start = time.perf_counter() while step < end: n = min(256, end - step) ix = np.stack([stream.take() for _ in range(n)]) exposure += np.bincount(ix.ravel(), minlength=len(exposure)) sampling_hash.update(ix.tobytes()) gpu_ix = torch.as_tensor(ix, device=device) for j in range(n): graph(gpu_ix[j]) step += n torch.cuda.synchronize() training_seconds += time.perf_counter() - start values = graph.components.detach().cpu().tolist() if not all(math.isfinite(v) for v in values): raise FloatingPointError(f"Nonfinite component losses at {step}") measure(step, values) if not records or records[-1]["step"] != spec["steps"]: raise ValueError("Budget not reached") write_json( out / "complete.json", { "spec": spec, "completed_utc": utc(), "capture_restore_passed": capture_ok, "training_seconds": training_seconds, "endpoint": records[-1], "initial_model_sha256": tensor_digest(origin["model"]), "final_model_sha256": tensor_digest(model.state_dict()), "exposure_sha256": hashlib.sha256(exposure.tobytes()).hexdigest(), "sampling_segment_sha256": sampling_hash.hexdigest(), "segment_start": current["step"] if resume else 0, }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs."""
from __future__ import annotations
import jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_model import ModelConfigfrom .grok_depth import GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_data import StratifiedStreamfrom .grok_loop_model import LoopGPT, flopsfrom .grok_multihop import autonomous_calls, evaluate_rows, pack_rows
def run(spec, world, out, device="cuda:0", resume=False): out = Path(out) out.mkdir(parents=True, exist_ok=True) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.manual_seed(spec["initialization"]) torch.cuda.manual_seed_all(spec["initialization"]) device = torch.device(device) torch.cuda.set_device(device) padded_length = spec["hops"] + 2 cfg = ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) model = LoopGPT( cfg, repeats=spec["repeats"], dropout=spec["dropout"], initialization=spec["init_scheme"], ).to(device) lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) opt = make_optimizer(model, lr, spec["weight_decay"]) atoms = pack_rows(world["atomic"], padded_length) comps = pack_rows(world["train_composite"], padded_length) table = tuple( torch.as_tensor(np.concatenate([a, c]), device=device) for a, c in zip(atoms, comps, strict=True) ) stream = StratifiedStream( len(world["atomic"]), len(world["train_composite"]), spec["batch_size"], spec["n_atomic_per_batch"], spec["stream_seed"], ) counts = {"atomic": 0, "composite": 0} elapsed_training, elapsed_eval = 0.0, 0.0 start_step = 0 checkpoint = out / "latest.pt" if resume: state = torch.load(checkpoint, map_location=device, weights_only=False) if state["spec"] != spec: raise ValueError("Resume spec differs from saved state") model.load_state_dict(state["model"]) opt.load_state_dict(state["optimizer"]) lr = opt.param_groups[0]["lr"] for group in opt.param_groups: group["lr"] = lr stream.load_state_dict(state["stream"]) counts = state["counts"] elapsed_training = state["elapsed_training"] elapsed_eval = state["elapsed_eval"] start_step = state["step"] torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) started = time.perf_counter() graph = GraphStep(model, opt, table, spec["batch_size"]) capture_seconds = time.perf_counter() - started names = ( "atomic", "id_atomic", "ood_atomic", "train_composite", "test_composite", "ood_composite", ) nparams = sum(p.numel() for p in model.parameters()) flop_step = flops( cfg, spec["repeats"], spec["batch_size"], sequence=padded_length, output_positions=2 ) rows_log = [] if (out / "learning.json").exists(): rows_log = json.loads((out / "learning.json").read_text()) if resume: rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) rows_log.sort(key=lambda row: row["step"])
def measure(step, last_loss=None): nonlocal elapsed_eval torch.cuda.synchronize() t0 = time.perf_counter() row = { "step": step, "utc": utc(), "hops": spec["hops"], "parameters": nparams, "unique_layers": spec["layers"], "repeats": spec["repeats"], "effective_depth": spec["layers"] * spec["repeats"], "training_seconds": elapsed_training, "capture_seconds": capture_seconds, "examples": step * spec["batch_size"], "counts": counts.copy(), "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, "supervised_tokens": step * spec["batch_size"] * 2, "estimated_training_flops": step * flop_step, "last_batch_loss": last_loss, } predictions = {} selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) for name in selected_names: row[name], pred = evaluate_rows(model, world[name], device, padded_length) predictions.update({name + "_" + key: value for key, value in pred.items()}) row["autonomous_calls"], calls_pred = autonomous_calls( model, world["test_composite"], world, device, padded_length ) predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) torch.cuda.synchronize() elapsed_eval += time.perf_counter() - t0 row["evaluation_seconds"] = elapsed_eval rows_log.append(row) write_json(out / "learning.json", rows_log) np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) state = { "step": step, "spec": spec, "model": model.state_dict(), "optimizer": opt.state_dict(), "stream": stream.state_dict(), "counts": counts, "elapsed_training": elapsed_training, "elapsed_eval": elapsed_eval, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(checkpoint) if step in spec["weight_nodes"]: torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"weights-{step:07d}.pt", ) status = { "state": "complete" if step == spec["steps"] else "running", "step": step, "budget": spec["steps"], "updated_utc": utc(), "hops": spec["hops"], "layers": spec["layers"], "atomic": row["atomic"]["accuracy"], "train": row["train_composite"]["accuracy"], "test_probe": row["test_composite"]["accuracy"], } write_json(out / "status.json", status) print(json.dumps(status), flush=True) return row
if not resume: measure(0) if start_step < spec["steps"]: for end in (s for s in spec["nodes"] if s > start_step): last_loss = None torch.cuda.synchronize() t0 = time.perf_counter() step = start_step while step < end: n = min(512, end - step) ix = np.stack([stream.take() for _ in range(n)]) atom_count = int((ix < len(world["atomic"])).sum()) counts["atomic"] += atom_count counts["composite"] += ix.size - atom_count gpu_ix = torch.as_tensor(ix, device=device) for j in range(n): lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) last_loss = graph(gpu_ix[j]) step += n torch.cuda.synchronize() elapsed_training += time.perf_counter() - t0 loss_value = float(last_loss.detach()) if not math.isfinite(loss_value): raise FloatingPointError(f"Nonfinite loss at step {end}") measure(end, loss_value) start_step = end if not rows_log or rows_log[-1]["step"] != spec["steps"]: raise ValueError("Evaluation nodes did not reach the fixed budget") write_json( out / "complete.json", { "finished_utc": utc(), "spec": spec, "parameters": nparams, "unique_layers": spec["layers"], "repeats": spec["repeats"], "effective_depth": spec["layers"] * spec["repeats"], "training_seconds": elapsed_training, "evaluation_seconds": elapsed_eval, "endpoint": rows_log[-1], }, ) return rows_log[-1]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""Longer-path trainer reusing the historical GPT, optimizer and graph step.
The only task changes are longer input rows and the separately audited split.Training uses the same uniform combined-set epochs and tail-plus-EOS loss."""
from __future__ import annotations
import jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfig, matmul_flopsfrom .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_jsonfrom .grok_multihop_data import path_details
def pack_rows(rows, padded_length): rows = np.asarray(rows, dtype=np.int64) if rows.ndim != 2 or rows.shape[1] > padded_length or rows.shape[1] < 3: raise ValueError("Rows must fit the fixed padded length and include an answer") x = np.zeros((len(rows), padded_length), dtype=np.int64) x[:, : rows.shape[1]] = rows positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] return x, positions, labels
@torch.no_grad()def evaluate_rows(model, rows, device, padded_length, batch_size=1024): was_training = model.training model.eval() packed = pack_rows(rows, padded_length) answers, stops, losses = [], [], [] for start in range(0, len(rows), batch_size): x, positions, labels = ( torch.as_tensor(a[start : start + batch_size], device=device) for a in packed ) # as_tensor shares CPU memory when device=cpu; all writes occur in a copy. x = x.clone() logits = model(x, positions) losses.append( F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") .view(-1, 2) .cpu() .numpy() ) answer = logits[:, 0].argmax(-1) x[torch.arange(len(x), device=device), positions[:, 1]] = answer stop = model(x, positions)[:, 1].argmax(-1) answers.append(answer.cpu().numpy()) stops.append(stop.cpu().numpy()) model.train(was_training) if not len(rows): return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) correct = answer == rows[:, -1] return { "n": len(rows), "answer_accuracy": float(correct.mean()), "accuracy": float((correct & (stop == 1)).mean()), "nll": float(nll.mean()), }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]}
@torch.no_grad()def autonomous_calls(model, rows, world, device, padded_length): """Supply relation decomposition, but carry the model's own intermediate answers.""" if not len(rows): return {"n": 0, "answer_accuracy": None, "accuracy": None}, {} meta = world["metadata"] nodes, _ = path_details(rows, world["atomic"], meta["entities"], meta["relations"]) current = rows[:, 0].copy() all_eos = np.ones(len(rows), dtype=bool) all_correct = np.ones(len(rows), dtype=bool) predictions, hop_accuracy = {}, [] for j in range(meta["hops"]): # Gold target only scores the answer; causality prevents answer-label access. queries = np.c_[current, rows[:, j + 1], nodes[:, j + 1]] metrics, pred = evaluate_rows(model, queries, device, padded_length) current = pred["answer"] all_eos &= pred["stop"] == 1 all_correct &= current == nodes[:, j + 1] hop_accuracy.append(metrics["accuracy"]) predictions[f"hop{j + 1}_answer"] = current predictions[f"hop{j + 1}_stop"] = pred["stop"] return { "n": len(rows), "calls": meta["hops"], "answer_accuracy": float((current == rows[:, -1]).mean()), "accuracy": float(((current == rows[:, -1]) & all_eos).mean()), "all_intermediate_answers_and_eos_correct": float((all_correct & all_eos).mean()), "hop_accuracy": hop_accuracy, "extra_information": "given relation decomposition, own generated bridge entities", }, predictions
def run(spec, world, out, device="cuda:0", resume=False): out = Path(out) out.mkdir(parents=True, exist_ok=True) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.manual_seed(spec["initialization"]) torch.cuda.manual_seed_all(spec["initialization"]) device = torch.device(device) torch.cuda.set_device(device) padded_length = spec["hops"] + 2 cfg = ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) model = SmallGPT(cfg, spec["dropout"]).to(device) lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) opt = make_optimizer(model, lr, spec["weight_decay"]) atoms = pack_rows(world["atomic"], padded_length) comps = pack_rows(world["train_composite"], padded_length) table = tuple( torch.as_tensor(np.concatenate([a, c]), device=device) for a, c in zip(atoms, comps, strict=True) ) stream = EpochStream(len(table[0]), spec["stream_seed"]) counts = {"atomic": 0, "composite": 0} elapsed_training, elapsed_eval = 0.0, 0.0 start_step = 0 checkpoint = out / "latest.pt" if resume: state = torch.load(checkpoint, map_location=device, weights_only=False) if state["spec"] != spec: raise ValueError("Resume spec differs from saved state") model.load_state_dict(state["model"]) opt.load_state_dict(state["optimizer"]) lr = opt.param_groups[0]["lr"] for group in opt.param_groups: group["lr"] = lr stream.load_state_dict(state["stream"]) counts = state["counts"] elapsed_training = state["elapsed_training"] elapsed_eval = state["elapsed_eval"] start_step = state["step"] torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) started = time.perf_counter() graph = GraphStep(model, opt, table, spec["batch_size"]) capture_seconds = time.perf_counter() - started names = ( "atomic", "id_atomic", "ood_atomic", "train_composite", "test_composite", "ood_composite", ) nparams = sum(p.numel() for p in model.parameters()) flop_step = matmul_flops(cfg, spec["batch_size"], sequence=padded_length, output_positions=2) rows_log = [] if (out / "learning.json").exists(): rows_log = json.loads((out / "learning.json").read_text()) if resume: rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) rows_log.sort(key=lambda row: row["step"])
def measure(step, last_loss=None): nonlocal elapsed_eval torch.cuda.synchronize() t0 = time.perf_counter() row = { "step": step, "utc": utc(), "hops": spec["hops"], "parameters": nparams, "training_seconds": elapsed_training, "capture_seconds": capture_seconds, "examples": step * spec["batch_size"], "counts": counts.copy(), "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, "supervised_tokens": step * spec["batch_size"] * 2, "estimated_training_flops": step * flop_step, "last_batch_loss": last_loss, } predictions = {} selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) for name in selected_names: row[name], pred = evaluate_rows(model, world[name], device, padded_length) predictions.update({name + "_" + key: value for key, value in pred.items()}) row["autonomous_calls"], calls_pred = autonomous_calls( model, world["test_composite"], world, device, padded_length ) predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) torch.cuda.synchronize() elapsed_eval += time.perf_counter() - t0 row["evaluation_seconds"] = elapsed_eval rows_log.append(row) write_json(out / "learning.json", rows_log) np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) state = { "step": step, "spec": spec, "model": model.state_dict(), "optimizer": opt.state_dict(), "stream": stream.state_dict(), "counts": counts, "elapsed_training": elapsed_training, "elapsed_eval": elapsed_eval, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(checkpoint) if step in spec["weight_nodes"]: torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"weights-{step:07d}.pt", ) status = { "state": "complete" if step == spec["steps"] else "running", "step": step, "budget": spec["steps"], "updated_utc": utc(), "hops": spec["hops"], "layers": spec["layers"], "atomic": row["atomic"]["accuracy"], "train": row["train_composite"]["accuracy"], "test_probe": row["test_composite"]["accuracy"], } write_json(out / "status.json", status) print(json.dumps(status), flush=True) return row
if not resume: measure(0) if start_step < spec["steps"]: for end in (s for s in spec["nodes"] if s > start_step): last_loss = None torch.cuda.synchronize() t0 = time.perf_counter() step = start_step while step < end: n = min(512, end - step) ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) atom_count = int((ix < len(world["atomic"])).sum()) counts["atomic"] += atom_count counts["composite"] += ix.size - atom_count gpu_ix = torch.as_tensor(ix, device=device) for j in range(n): lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) last_loss = graph(gpu_ix[j]) step += n torch.cuda.synchronize() elapsed_training += time.perf_counter() - t0 loss_value = float(last_loss.detach()) if not math.isfinite(loss_value): raise FloatingPointError(f"Nonfinite loss at step {end}") measure(end, loss_value) start_step = end if not rows_log or rows_log[-1]["step"] != spec["steps"]: raise ValueError("Evaluation nodes did not reach the fixed budget") write_json( out / "complete.json", { "finished_utc": utc(), "spec": spec, "parameters": nparams, "training_seconds": elapsed_training, "evaluation_seconds": elapsed_eval, "endpoint": rows_log[-1], }, ) return rows_log[-1]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""Separate longer-path extension of the audited two-hop random-world task.
The graph and atomic split are reused exactly. A run trains all atomics andone explicitly specified path length; no intermediate entities are targets.Complete queries, not constituent facts or subpaths, define held-out examples."""
from __future__ import annotations
import hashlibimport math
import numpy as np
from .grok_depth_data import ENTITY_OFFSETfrom .grok_depth_data import build_world as build_twohop_world
SPLITS = ( "atomic", "id_atomic", "ood_atomic", "train_composite", "test_composite", "test_full_composite", "ood_composite", "unused_composite",)
def path_details(rows, atomic, entities, relations): """Return the actual entity trajectory and atomic row indices at each hop.""" offset = ENTITY_OFFSET + entities lookup = np.full((entities, relations), -1, dtype=np.int64) lookup[atomic[:, 0] - ENTITY_OFFSET, atomic[:, 1] - offset] = np.arange(len(atomic)) nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64) edges = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64) nodes[:, 0] = rows[:, 0] for j in range(edges.shape[1]): indices = lookup[nodes[:, j] - ENTITY_OFFSET, rows[:, j + 1] - offset] if np.any(indices < 0): raise ValueError("Path references a missing atomic fact") edges[:, j] = indices nodes[:, j + 1] = atomic[indices, -1] if np.any(nodes[:, -1] != rows[:, -1]): raise ValueError("Path target disagrees with atomic facts") return nodes, edges
def _diagnostics(rows, atomic, entities, relations, id_mask): nodes, edges = path_details(rows, atomic, entities, relations) repeated = np.zeros(len(rows), dtype=bool) for j in range(1, nodes.shape[1]): repeated |= (nodes[:, j, None] == nodes[:, :j]).any(axis=1) positional = [] for j in range(edges.shape[1]): counts = np.bincount(edges[:, j], minlength=len(atomic)) positional.append( { "hop": j + 1, "id_edges_covered": int((counts[id_mask] > 0).sum()), "id_edges_total": int(id_mask.sum()), "counts_per_atomic_edge": counts.tolist(), "id_count_min": int(counts[id_mask].min()) if id_mask.any() else None, "id_count_max": int(counts[id_mask].max()) if id_mask.any() else None, } ) return { "n": len(rows), "any_repeated_entity_n": int(repeated.sum()), "any_repeated_entity_fraction": float(repeated.mean()) if len(rows) else None, "answer_equals_preceding_entity_n": int( (nodes[:, -1, None] == nodes[:, :-1]).any(axis=1).sum() ), "edge_positions": positional, }
def build_world( seed, hops=3, entities=128, relations=16, degree=8, phi=6.0, id_fraction=0.95, id_test_fraction=0.1, evaluation_size=1024,): """Enumerate all paths, reserve test queries, then sample training queries.
The fixed per-node evaluation subset is sampled from the entire reserved test pool without consulting training or predictions. Endpoints evaluate that full pool too. Mixed-ID/OOD paths remain excluded, as before. """ if not isinstance(hops, int) or isinstance(hops, bool) or not 2 <= hops <= 4: raise ValueError("hops must be an integer from 2 through 4") if not isinstance(evaluation_size, int) or evaluation_size < 1: raise ValueError("evaluation_size must be a positive integer") if not math.isfinite(phi) or phi < 0: raise ValueError("phi must be finite and nonnegative") base = build_twohop_world(seed, entities, relations, degree, 0.0, id_fraction, id_test_fraction) atomic = base["atomic"] ood_set = {tuple(row) for row in base["ood_atomic"]} ood_mask = np.array([tuple(row) in ood_set for row in atomic]) rows = atomic.copy() all_id, all_ood = ~ood_mask, ood_mask.copy() for _ in range(1, hops): following = (rows[:, -1, None] - ENTITY_OFFSET) * degree + np.arange(degree) following = following.reshape(-1) prefix = np.repeat(rows[:, :-1], degree, axis=0) rows = np.c_[prefix, atomic[following, 1:]] all_id = np.repeat(all_id, degree) & ~ood_mask[following] all_ood = np.repeat(all_ood, degree) & ood_mask[following] id_rows = rows[all_id] rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144001])) test_mask = rng.random(len(id_rows)) < id_test_fraction test_full = id_rows[test_mask] eligible = id_rows[~test_mask] probe_rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144002])) probe_indices = probe_rng.choice( len(test_full), size=min(evaluation_size, len(test_full)), replace=False ) requested = round(phi * len(base["id_atomic"])) ntrain = min(requested, len(eligible)) indices = rng.choice(len(eligible), size=ntrain, replace=False) train_mask = np.zeros(len(eligible), dtype=bool) train_mask[indices] = True world = { "atomic": atomic, "id_atomic": base["id_atomic"], "ood_atomic": base["ood_atomic"], "train_composite": eligible[indices], "test_composite": test_full[probe_indices], "test_full_composite": test_full, "ood_composite": rows[all_ood], "unused_composite": eligible[~train_mask], "metadata": { **base["metadata"], "hops": hops, "task": "all atomic facts plus one target composition length", "phi_requested": phi, "phi_actual": ntrain / max(len(base["id_atomic"]), 1), "train_composite_requested": requested, "train_composite_capped": requested > len(eligible), "id_paths_total": len(id_rows), "all_paths_total": len(rows), "mixed_composite_excluded": int((~all_id & ~all_ood).sum()), "training_fraction_of_id_paths": ntrain / max(len(id_rows), 1), "training_fraction_of_nonreserved_id_paths": ntrain / max(len(eligible), 1), "evaluation_size_requested": evaluation_size, "probe_indices_in_full_test": probe_indices.tolist(), "split_rng": "default_rng(SeedSequence([world_seed,hops,144001]))", "probe_rng": "default_rng(SeedSequence([world_seed,hops,144002]))", "construction_differences": [ "same graph and atomic split as historical two-hop constructor", "enumerated target length 2/3/4; only one length enters a run", "fresh deterministic complete-path reserve and phi downsampling", "fixed test probe at every node; entire reserve evaluated at endpoint", ], "warnings": [ warning for condition, warning in ( (not len(test_full), "No reserved ID paths; never regenerate the world"), (not int(all_ood.sum()), "No all-OOD paths; report zero denominator"), (requested > len(eligible), "Training request capped at eligible pool"), ) if condition ], }, } audit = audit_world(world) world["metadata"]["counts"] = audit["counts"] world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] world["metadata"]["diagnostics"] = { name: _diagnostics(world[name], atomic, entities, relations, ~ood_mask) for name in ("train_composite", "test_composite", "test_full_composite") } return world
def audit_world(world): """Independent graph truth, split completeness and full-query leakage checks.""" meta = world["metadata"] entities, relations, hops = (int(meta[k]) for k in ("entities", "relations", "hops")) offset = ENTITY_OFFSET + entities digest = hashlib.sha256() counts = {} for name in SPLITS: rows = world[name] columns = 3 if name.endswith("atomic") else hops + 2 if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != columns: raise ValueError(f"Invalid shape or dtype: {name}") if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= offset)): raise ValueError(f"Invalid entity tokens: {name}") if np.any((rows[:, 1:-1] < offset) | (rows[:, 1:-1] >= offset + relations)): raise ValueError(f"Invalid relation tokens: {name}") if len(np.unique(rows[:, :-1], axis=0)) != len(rows): raise ValueError(f"Duplicate complete queries: {name}") path_details(rows, world["atomic"], entities, relations) counts[name] = len(rows) digest.update(name.encode()) digest.update(np.asarray(rows.shape, dtype="<i8").tobytes()) digest.update(rows.astype("<i8", copy=False).tobytes()) atoms = {tuple(row) for row in world["atomic"]} ids = {tuple(row) for row in world["id_atomic"]} oods = {tuple(row) for row in world["ood_atomic"]} if ids & oods or ids | oods != atoms: raise ValueError("Atomic ID/OOD split is not a partition") is_id = np.array([tuple(row) in ids for row in world["atomic"]]) primary = ("train_composite", "test_full_composite", "unused_composite", "ood_composite") joined = np.concatenate([world[name] for name in primary]) if len(np.unique(joined[:, :-1], axis=0)) != len(joined): raise ValueError("Complete queries overlap across train/reserve/unused/OOD") for name in primary: _, edges = path_details(world[name], world["atomic"], entities, relations) expected = ~is_id[edges] if name == "ood_composite" else is_id[edges] if not expected.all(): raise ValueError(f"Incorrect atomic split along path: {name}") lookup = np.zeros((entities, relations), dtype=np.int64) id_lookup = lookup.copy() atomic = world["atomic"] for mask, table in ((is_id, id_lookup), (~is_id, lookup)): table.fill(-1) table[atomic[mask, 0] - ENTITY_OFFSET, atomic[mask, 1] - offset] = ( atomic[mask, -1] - ENTITY_OFFSET ) totals = [] for table in (id_lookup, lookup): path_counts = np.ones(entities, dtype=np.int64) for _ in range(hops): path_counts = np.where(table >= 0, path_counts[np.maximum(table, 0)], 0).sum(1) totals.append(int(path_counts.sum())) if sum(counts[k] for k in primary[:3]) != totals[0] or counts[primary[3]] != totals[1]: raise ValueError("Path partitions are not exhaustive") probes = np.asarray(meta["probe_indices_in_full_test"], dtype=np.int64) if not np.array_equal(world["test_composite"], world["test_full_composite"][probes]): raise ValueError("Fixed test probe differs from its recorded full-pool indices") return { "counts": counts, "dataset_sha256": digest.hexdigest(), "id_paths_independently_counted": totals[0], "ood_paths_independently_counted": totals[1], "complete_query_overlap": 0, "atomic_facts_intentionally_shared_with_test": True, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""Paired fact-use assignments and constituent-occurrence repetition controls.
The same random graph and held-out queries are used in every arm. A/B changewhich random fact cohort may occur in composition training. repA/repB replaceeach selected role-composition slot with its two constituent atomic queries;their half-weight losses preserve slot weight, not information or computation."""
from __future__ import annotations
import copyimport hashlibfrom collections.abc import Mapping
import numpy as np
from .grok_depth_data import build_world as build_graph_worldfrom .grok_loop_data import _EpochStream
GROUP_NAMES = ("BG", "A", "B")ARMS = ("A", "B", "repA", "repB")ROW_KINDS = ("base_atomic", "background_composite", "role_composite", "repetition_atomic")
def _digest(arrays: Mapping[str, np.ndarray]) -> str: digest = hashlib.sha256() for name in sorted(arrays): array = np.asarray(arrays[name], dtype="<i8") digest.update(name.encode()) digest.update(np.asarray(array.shape, dtype="<i8").tobytes()) digest.update(array.tobytes()) return digest.hexdigest()
def _fact_counts(indices: np.ndarray, n_atomic: int) -> np.ndarray: return np.bincount(indices[indices >= 0], minlength=n_atomic).astype(np.int64)
def build_experiment(spec: Mapping) -> dict: """Build one graph, one global reserve, and paired composition pools.
Defaults are 128 entities, 16 relations, outdegree 8, and a 10% Bernoulli complete-query reserve. A/B cohorts each contain floor(n_atomic/4) facts; all remaining facts form the shared background. Cohort assignment and the reserve have independent RNGs and never depend on predictions. Role pools are uniformly downsampled to their smaller available size. Background paths are used exhaustively. Empty sampled strata raise without resampling. """ seed = int(spec.get("world_seed", spec.get("seed", 146001))) entities = int(spec.get("entities", 128)) relations = int(spec.get("relations", 16)) degree = int(spec.get("degree", 8)) reserve_fraction = float(spec.get("test_fraction", 0.1)) if spec.get("hops", 2) != 2: raise ValueError("This comparison is defined only for two hops") if not np.isfinite(reserve_fraction) or not 0 < reserve_fraction < 1: raise ValueError("test_fraction must lie strictly between zero and one") base = build_graph_world( seed, entities, relations, degree, phi=0, id_fraction=1, id_test_fraction=0 ) atomic = base["atomic"].copy() n_atomic = len(atomic) cohort_size = n_atomic // 4 if not cohort_size: raise ValueError("At least four atomic facts are required") # All paths use the stable per-head block ordering of the inherited graph. second = ((atomic[:, -1, None] - 2) * degree + np.arange(degree)).reshape(-1) first = np.repeat(np.arange(n_atomic, dtype=np.int64), degree) all_edges = np.c_[first, second] all_rows = np.c_[atomic[first, :2], atomic[second, 1:]] reserve_rng = np.random.default_rng(np.random.SeedSequence([seed, 146101])) heldout = reserve_rng.random(len(all_rows)) < reserve_fraction assignment_rng = np.random.default_rng(np.random.SeedSequence([seed, 146102])) assignment = assignment_rng.permutation(n_atomic) groups = np.zeros(n_atomic, dtype=np.int64) groups[assignment[:cohort_size]] = 1 groups[assignment[cohort_size : 2 * cohort_size]] = 2 path_groups = groups[all_edges] background_indices = np.flatnonzero(~heldout & (path_groups == 0).all(axis=1)) role_candidates = {} for name, group in (("A", 1), ("B", 2)): eligible = ((path_groups == 0) | (path_groups == group)).all(axis=1) role_candidates[name] = np.flatnonzero( ~heldout & eligible & (path_groups == group).any(axis=1) ) role_size = min(map(len, role_candidates.values())) if not len(background_indices) or not role_size: raise ValueError("Empty training stratum; retain the supplied world, do not reroll") selected = {} for name, group in (("A", 1), ("B", 2)): rng = np.random.default_rng(np.random.SeedSequence([seed, 146103, group])) selected[name] = rng.choice(role_candidates[name], size=role_size, replace=False) exp = { "atomic": atomic, "fact_groups": groups, "all_composite": all_rows, "all_composite_fact_indices": all_edges, "heldout_mask": heldout, "test_composite": all_rows[heldout], "test_composite_fact_indices": all_edges[heldout], "background_composite": all_rows[background_indices], "background_fact_indices": all_edges[background_indices], "role_A_composite": all_rows[selected["A"]], "role_A_fact_indices": all_edges[selected["A"]], "role_B_composite": all_rows[selected["B"]], "role_B_fact_indices": all_edges[selected["B"]], "metadata": { "world_seed": seed, "seed": seed, "entities": entities, "relations": relations, "degree": degree, "hops": 2, "vocab_size": 2 + entities + relations, "test_fraction": reserve_fraction, "cohort_assignment_rng": "SeedSequence([world_seed,146102])", "complete_query_reserve_rng": "SeedSequence([world_seed,146101])", "role_pool_rng": "SeedSequence([world_seed,146103,group])", "group_names": list(GROUP_NAMES), "group_sizes": [int((groups == group).sum()) for group in range(3)], "role_candidate_sizes": {name: len(rows) for name, rows in role_candidates.items()}, "role_pool_size": role_size, "background_pool_size": len(background_indices), "test_queries": int(heldout.sum()), "all_queries": len(all_rows), "source_graph_sha256": base["metadata"]["dataset_sha256"], "source_graph_constructor": "grok_depth_data.build_world (atomic graph only)", "role_meaning": "random eligibility; actual per-fact occurrence counts also reported", "selection": "one supplied graph; no data or model-score based seed selection", }, } for name in ("background", "role_A", "role_B"): counts = _fact_counts(exp[name + "_fact_indices"], n_atomic) exp["metadata"][name + "_fact_occurrence_counts"] = counts.tolist() exp["metadata"]["test_group_counts"] = { f"{left}_{right}": int( (heldout & (path_groups[:, 0] == i) & (path_groups[:, 1] == j)).sum() ) for i, left in enumerate(GROUP_NAMES) for j, right in enumerate(GROUP_NAMES) } audit = audit_experiment(exp) exp["metadata"]["dataset_sha256"] = audit["dataset_sha256"] return exp
def audit_experiment(exp: dict) -> dict: """Reconstruct truth and verify the global reserve and swapped eligibility.""" atomic, groups, meta = exp["atomic"], exp["fact_groups"], exp["metadata"] if atomic.dtype != np.int64 or groups.dtype != np.int64 or len(groups) != len(atomic): raise ValueError("Invalid atomic or group arrays") if np.any((groups < 0) | (groups > 2)): raise ValueError("Invalid fact group") lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atomic)} if len(lookup) != len(atomic): raise ValueError("Duplicate atomic queries") heldout_queries = {tuple(row[:-1]) for row in exp["test_composite"]} if len(heldout_queries) != len(exp["test_composite"]): raise ValueError("Duplicate held-out query") arrays = {"atomic": atomic, "fact_groups": groups} for name in ("all", "test", "background", "role_A", "role_B"): rows = exp[name + "_composite"] index_key = ( name + "_composite_fact_indices" if name in ("all", "test") else name + "_fact_indices" ) recorded = exp[index_key] expected = np.empty((len(rows), 2), dtype=np.int64) seen = set() for i, (h, r1, r2, t) in enumerate(rows): query = (int(h), int(r1), int(r2)) if query in seen: raise ValueError(f"Duplicate query in {name}") seen.add(query) try: bridge, first = lookup[int(h), int(r1)] target, second = lookup[bridge, int(r2)] except KeyError as error: raise ValueError(f"Missing path fact in {name}") from error if target != t: raise ValueError(f"Wrong path target in {name}") expected[i] = first, second if name in ("background", "role_A", "role_B") and query in heldout_queries: raise ValueError("Held-out query leaked into training") if not np.array_equal(recorded, expected): raise ValueError(f"Incorrect fact indices in {name}") if name == "background" and np.any(groups[expected] != 0): raise ValueError("Background pool uses a treatment fact") if name in ("role_A", "role_B"): role = 1 if name == "role_A" else 2 actual_groups = groups[expected] if np.any((actual_groups != 0) & (actual_groups != role)): raise ValueError("Role pool uses the opposite cohort") if np.any(~(actual_groups == role).any(axis=1)): raise ValueError("Role pool contains a background-only path") arrays[name] = rows arrays[index_key] = recorded if len(exp["all_composite"]) != len(atomic) * int(meta["degree"]): raise ValueError("Incomplete full path enumeration") if not np.array_equal(exp["all_composite"][exp["heldout_mask"]], exp["test_composite"]): raise ValueError("Global held-out mask disagrees with test queries") if len(exp["role_A_composite"]) != len(exp["role_B_composite"]): raise ValueError("Paired role pools differ in size") digest = _digest(arrays) recorded_digest = meta.get("dataset_sha256") if recorded_digest is not None and recorded_digest != digest: raise ValueError("Recorded dataset hash differs from arrays") return {"passed": True, "dataset_sha256": digest, "test_queries": len(heldout_queries)}
def build_arm_world(exp: dict, arm: str) -> dict: """Return packed-table ingredients, evaluation sets and exposure provenance.
Concatenate ``pack_rows(part['rows'], 4)`` in ``training_parts`` order. ``table_weights`` and ``table_fact_indices`` align with that concatenation. An atomic row has one fact id and -1; a composition row has two ids. Thus raw fact occurrences can be accumulated without interpreting token counts or claiming equal supervision/information. rep arms keep the same role path reference pool for paired evaluation, but do not train those queries. """ if arm not in ARMS: raise ValueError(f"Unknown arm: {arm}") role_name = arm[-1] repeat = arm.startswith("rep") atomic = exp["atomic"] n_atomic = len(atomic) atom_indices = np.c_[np.arange(n_atomic), np.full(n_atomic, -1)].astype(np.int64) role_edges = exp[f"role_{role_name}_fact_indices"] role_rows = exp[f"role_{role_name}_composite"] if repeat: last_rows = atomic[role_edges.ravel()] last_edges = np.c_[role_edges.ravel(), np.full(role_edges.size, -1)].astype(np.int64) else: last_rows, last_edges = role_rows, role_edges parts = [ { "name": "atomic", "rows": atomic, "weights": np.ones(n_atomic, dtype=np.float32), "fact_indices": atom_indices, }, { "name": "background", "rows": exp["background_composite"], "weights": np.ones(len(exp["background_composite"]), dtype=np.float32), "fact_indices": exp["background_fact_indices"], }, { "name": "repetition" if repeat else "role", "rows": last_rows, "weights": np.full(len(last_rows), 0.5 if repeat else 1, dtype=np.float32), "fact_indices": last_edges, }, ] evaluation = {"atomic": atomic} for group, name in enumerate(GROUP_NAMES): evaluation[f"atomic_{name}"] = atomic[exp["fact_groups"] == group] evaluation["test_composite"] = exp["test_composite"] query_groups = exp["fact_groups"][exp["test_composite_fact_indices"]] for i, left in enumerate(GROUP_NAMES): for j, right in enumerate(GROUP_NAMES): mask = (query_groups[:, 0] == i) & (query_groups[:, 1] == j) evaluation[f"test_{left}_{right}"] = exp["test_composite"][mask] evaluation["train_background"] = exp["background_composite"] evaluation["role_A_reference"] = exp["role_A_composite"] evaluation["role_B_reference"] = exp["role_B_composite"] train_composite = ( exp["background_composite"] if repeat else np.concatenate([exp["background_composite"], role_rows]) ) evaluation["train_composite"] = train_composite group_id = 1 if role_name == "A" else 2 eligible = (exp["fact_groups"] == 0) | ((exp["fact_groups"] == group_id) & (not repeat)) used_counts = _fact_counts( np.concatenate( [exp["background_fact_indices"], role_edges if not repeat else role_edges[:0]] ), n_atomic, ) world = { "arm": arm, "atomic": atomic, "id_atomic": atomic[eligible], "ood_atomic": atomic[~eligible], "background_composite": exp["background_composite"], "role_composite": role_rows, "train_composite": train_composite, "test_composite": exp["test_composite"], "test_full_composite": exp["test_composite"], "training_parts": parts, "table_weights": np.concatenate([part["weights"] for part in parts]), "table_fact_indices": np.concatenate([part["fact_indices"] for part in parts]), "table_row_kinds": np.concatenate( [ np.full(len(part["rows"]), kind, dtype=np.int64) for part, kind in zip(parts, [0, 1, 3 if repeat else 2], strict=True) ] ), "evaluation": evaluation, "metadata": { **copy.deepcopy(exp["metadata"]), "arm": arm, "repetition_control": repeat, "role_name": role_name, "row_kind_names": list(ROW_KINDS), "training_composite_fact_occurrence_counts": used_counts.tolist(), "eligible_facts_without_actual_composite_occurrence": int( (eligible & (used_counts == 0)).sum() ), "evaluation_note": "same global heldout and nine cohort-pair strata in every arm", "repetition_note": ( "two constituent atomics per role slot, each loss weight 1/2; matches raw " "constituent occurrences, not information, direct supervision or compute" ), }, } return world
class UsageStream: """Emit paired base/background/role slots, expanding rep slots into two rows."""
def __init__(self, world, seed, n_atomic=32, n_background=112, n_role=112): for name, value in ( ("n_atomic", n_atomic), ("n_background", n_background), ("n_role", n_role), ): if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: raise ValueError(f"{name} must be a positive integer") self.arm = world["arm"] self.repeat = self.arm.startswith("rep") self.atomic_size = len(world["atomic"]) self.background_size = len(world["background_composite"]) self.role_size = len(world["role_composite"]) self.n_atomic, self.n_background, self.n_role = ( int(n_atomic), int(n_background), int(n_role), ) if min(self.atomic_size, self.background_size, self.role_size) < 1: raise ValueError("Sampled strata cannot be empty") self.nominal_batch_size = self.n_atomic + self.n_background + self.n_role self.batch_size = self.nominal_batch_size + (self.n_role if self.repeat else 0) self.atomic = _EpochStream(self.atomic_size, np.random.SeedSequence([int(seed), 146201])) self.background = _EpochStream( self.background_size, np.random.SeedSequence([int(seed), 146202]) ) self.role = _EpochStream(self.role_size, np.random.SeedSequence([int(seed), 146203])) self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 146204])) self.batches = 0
def take(self, n=None): if n is not None and n != self.batch_size: raise ValueError("UsageStream emits its configured actual batch size") atoms = self.atomic.take(self.n_atomic) background = self.background.take(self.n_background) + self.atomic_size role = self.role.take(self.n_role) if self.repeat: role = (role[:, None] * 2 + np.arange(2)).ravel() role = role + self.atomic_size + self.background_size indices = np.r_[atoms, background, role] self.batches += 1 return indices[self.interleave.permutation(self.batch_size)]
def state_dict(self): return { "version": 1, "arm": self.arm, "n_atomic": self.n_atomic, "n_background": self.n_background, "n_role": self.n_role, "atomic": self.atomic.state_dict(), "background": self.background.state_dict(), "role": self.role.state_dict(), "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), "batches": self.batches, }
def load_state_dict(self, state): if state.get("version") != 1: raise ValueError("Unsupported UsageStream state version") for name in ("arm", "n_atomic", "n_background", "n_role"): if state[name] != getattr(self, name): raise ValueError(f"UsageStream {name} mismatch") if not isinstance(state["batches"], int) or state["batches"] < 0: raise ValueError("Invalid batch count") replacements = {} for name in ("atomic", "background", "role"): replacements[name] = copy.deepcopy(getattr(self, name)) replacements[name].load_state_dict(state[name]) interleave = copy.deepcopy(self.interleave) interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) for name, stream in replacements.items(): setattr(self, name, stream) self.interleave = interleave self.batches = state["batches"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""Paired training of composition experience versus constituent-fact repetition."""
from __future__ import annotations
import jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfigfrom .grok_depth import GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_model import LoopGPT, flopsfrom .grok_multihop import autonomous_calls, evaluate_rows, pack_rowsfrom .grok_usage_data import UsageStream
def weighted_loss(logits, labels, weights, normalizer): """Each logical slot has weight one; its two atomic substitutes have .5 each.""" losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") return (losses.view(-1, 2).mean(1) * weights).sum() / normalizer
class UsageGraphStep(GraphStep): def __init__(self, model, optimizer, table, batch_size, normalizer): self.normalizer = normalizer super().__init__(model, optimizer, table, batch_size)
def eager(self): self.optimizer.zero_grad(set_to_none=False) x, positions, labels, weights = (t[self.index] for t in self.table) loss = weighted_loss(self.model(x, positions), labels, weights, self.normalizer) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def make_model(spec, device): cfg = ModelConfig( vocab_size=2 + spec["entities"] + spec["relations"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=8, ) return LoopGPT( cfg, repeats=spec["repeats"], dropout=spec["dropout"], initialization=spec["init_scheme"], ).to(device), cfg
def run(spec, world, out, device="cuda:0", resume=False): out = Path(out) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True device = torch.device(device) torch.cuda.set_device(device) torch.cuda.set_per_process_memory_fraction(spec.get("memory_fraction", 0.025), device) torch.manual_seed(spec["initialization"]) torch.cuda.manual_seed_all(spec["initialization"]) model, cfg = make_model(spec, device) lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) packed = [pack_rows(part["rows"], 4) for part in world["training_parts"]] table = tuple( torch.as_tensor(np.concatenate([part[j] for part in packed]), device=device) for j in range(3) ) + (torch.as_tensor(world["table_weights"], device=device, dtype=torch.float32),) stream = UsageStream( world, spec["stream_seed"], n_atomic=spec["n_atomic"], n_background=spec["n_background"], n_role=spec["n_role"], ) logical_batch = spec["n_atomic"] + spec["n_background"] + spec["n_role"] actual_batch = logical_batch + (spec["n_role"] if spec["arm"].startswith("rep") else 0) exposure = np.zeros((4, len(world["atomic"])), dtype=np.int64) kind_counts = np.zeros(4, dtype=np.int64) train_seconds, evaluation_seconds, start_step = 0.0, 0.0, 0 if resume: state = torch.load(out / "latest.pt", map_location=device, weights_only=False) if state["spec"] != spec: raise ValueError("Resume specification changed") model.load_state_dict(state["model"]) optimizer.load_state_dict(state["optimizer"]) lr = optimizer.param_groups[0]["lr"] for group in optimizer.param_groups: group["lr"] = lr stream.load_state_dict(state["stream"]) exposure, kind_counts = state["exposure"], state["kind_counts"] train_seconds, evaluation_seconds = state["training_seconds"], state["evaluation_seconds"] start_step = state["step"] torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) t0 = time.perf_counter() graph = UsageGraphStep(model, optimizer, table, actual_batch, logical_batch) capture_seconds = time.perf_counter() - t0 learning = json.loads((out / "learning.json").read_text()) if resume else [] learning = [row for row in learning if row["step"] <= start_step] fact_ids = np.asarray(world["table_fact_indices"]) kinds = np.asarray(world["table_row_kinds"]) flop_step = flops(cfg, spec["repeats"], actual_batch, sequence=4, output_positions=2)
def measure(step, last_loss=None): nonlocal evaluation_seconds torch.cuda.synchronize() before = time.perf_counter() metrics, predictions = {}, {} for name, rows in world["evaluation"].items(): metrics[name], pred = evaluate_rows(model, rows, device, 4) if len(rows): metrics[name]["answer_probability"] = float(np.exp(-pred["nll"][:, 0]).mean()) predictions.update({name + "_" + k: v for k, v in pred.items()}) metrics["autonomous_calls"], pred = autonomous_calls( model, world["evaluation"]["test_composite"], world, device, 4, ) predictions.update({"autonomous_" + k: v for k, v in pred.items()}) torch.cuda.synchronize() evaluation_seconds += time.perf_counter() - before row = { "step": step, "utc": utc(), "arm": spec["arm"], "world_seed": spec["world_seed"], "metrics": metrics, "last_batch_loss": last_loss, "training_seconds": train_seconds, "evaluation_seconds": evaluation_seconds, "capture_seconds": capture_seconds, "actual_examples": int(kind_counts.sum()), "logical_slots": step * logical_batch, "supervised_tokens": int(kind_counts.sum()) * 2, "effective_input_tokens": int((kind_counts * np.array([3, 4, 4, 3])).sum()), "estimated_training_flops": step * flop_step, "kind_counts": kind_counts.tolist(), } learning.append(row) write_json(out / "learning.json", learning) np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=exposure, kinds=kind_counts) state = { "spec": spec, "step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "stream": stream.state_dict(), "exposure": exposure, "kind_counts": kind_counts, "training_seconds": train_seconds, "evaluation_seconds": evaluation_seconds, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(out / "latest.pt") if step in spec["weight_nodes"]: torch.save( {"spec": spec, "step": step, "model": model.state_dict()}, out / f"weights-{step:07d}.pt", ) status = { "state": "trained" if step == spec["steps"] else "running", "step": step, "budget": spec["steps"], "arm": spec["arm"], "updated_utc": utc(), "test_composite": metrics["test_composite"]["accuracy"], "training_seconds": train_seconds, } write_json(out / "status.json", status) print(json.dumps(status), flush=True)
if not resume: measure(0) for end in (node for node in spec["nodes"] if node > start_step): torch.cuda.synchronize() before = time.perf_counter() step = start_step while step < end: n = min(512, end - step) indices = np.stack([stream.take() for _ in range(n)]) selected = indices.ravel() selected_kinds, selected_facts = kinds[selected], fact_ids[selected] kind_counts += np.bincount(selected_kinds, minlength=4) for kind in range(4): facts = selected_facts[selected_kinds == kind].ravel() exposure[kind] += np.bincount(facts[facts >= 0], minlength=exposure.shape[1]) gpu_indices = torch.as_tensor(indices, device=device) for j in range(n): lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) loss = graph(gpu_indices[j]) step += n torch.cuda.synchronize() train_seconds += time.perf_counter() - before loss_value = float(loss.detach()) if not math.isfinite(loss_value): raise FloatingPointError(f"Nonfinite loss at {end}") measure(end, loss_value) start_step = end if not learning or learning[-1]["step"] != spec["steps"]: raise ValueError("Registered nodes did not reach endpoint") # Reload every endpoint from disk and compare all saved per-example scores. saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) model.load_state_dict(saved["model"]) old = np.load(out / f"predictions-{spec['steps']:07d}.npz") errors, checks, largest_nll_difference = [], 0, 0.0 for name, rows in world["evaluation"].items(): _, pred = evaluate_rows(model, rows, device, 4) for key, value in pred.items(): reference = old[name + "_" + key] checks += len(value) if key == "nll": difference = float(np.abs(value - reference).max()) if len(value) else 0.0 largest_nll_difference = max(largest_nll_difference, difference) ok = np.allclose(value, reference, atol=1e-6, rtol=1e-6) else: ok = np.array_equal(value, reference) if not ok: errors.append(name + "_" + key) audit = { "checks": checks, "errors": errors, "max_nll_difference": largest_nll_difference, "method": "reload saved endpoint; all evaluation splits, identical GPU/dtype/batch shape", } write_json(out / "endpoint-audit.json", audit) if errors: raise ValueError(f"Endpoint reload failed: {errors}") write_json( out / "complete.json", { "finished_utc": utc(), "spec": spec, "endpoint": learning[-1], "audit": audit, "parameters": sum(p.numel() for p in model.parameters()), "maximum_allocated_bytes": torch.cuda.max_memory_allocated(device), }, ) write_json( out / "status.json", { "state": "complete", "step": spec["steps"], "arm": spec["arm"], "utc": utc(), }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421"""Pure first-hop state interventions and held-out, local fact-update branches.
The text template's factual answer is predicted at `is`, rather than at r1.All targets and donors are selected from the graph before model inference."""
from __future__ import annotations
import copyimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .depth_step_mechanism import traced_forwardfrom .grok_depth import write_jsonfrom .latent_scaling import model_digestfrom .storage_composition import generate_rows, pack_sentencesfrom .text_pretrain import atomic_sentence, composite_sentence
PARAMETER = "blocks.0.mlp.down.weight"
def taught_atoms(world): return np.concatenate([world["common_atomic"], world["anchor_atomic"]])
def update_case(world, atomic_index, group, replay_n=32, keep_n=32): """Change one graph edge; recompute the entire two-hop affected closure.""" atoms = taught_atoms(world) old = atoms[atomic_index].copy() lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} first_role = 13 <= old[1] <= 16 pool = world[group + "_test"] if first_role: affected = (pool[:, 0] == old[0]) & (pool[:, 1] == old[1]) relation_rows = pool[affected] options = sorted({int(row[2]) for row in atoms if 13 <= row[1] <= 16}) # Prefer the same familiar/strict bridge bank; all successor facts must be taught. own_bank = sorted({int(row[2]) for row in pool}) candidates = [v for v in own_bank if v != old[2]] + [ v for v in options if v != old[2] and v not in own_bank ] new_value = next( v for v in candidates if all((v, int(row[3])) in lookup for row in relation_rows) and any(lookup[v, int(row[3])] != row[4] for row in relation_rows) ) else: affected = (pool[:, 2] == old[0]) & (pool[:, 3] == old[1]) tails = sorted({int(row[2]) for row in atoms if 17 <= row[1] <= 20}) new_value = tails[(tails.index(int(old[2])) + 1) % len(tails)] new = old.copy() new[2] = new_value lookup[int(new[0]), int(new[1])] = int(new[2]) tasks = {"E_new": np.asarray([new]), "E_old": np.asarray([old])} original_d = {} successor_keys = set() for split in ["familiar", "strict"]: rows = world[split + "_test"] mask = ( ((rows[:, 0] == old[0]) & (rows[:, 1] == old[1])) if first_role else ((rows[:, 2] == old[0]) & (rows[:, 3] == old[1])) ) original = rows[mask].copy() changed = original.copy() for row in changed: row[2] = lookup[int(row[0]), int(row[1])] row[4] = lookup[int(row[2]), int(row[3])] successor_keys.add((int(row[2]), int(row[3]))) name = "D_" + split tasks[name] = changed original_d[name] = original tasks["U_" + split] = rows[~mask].copy() index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} successor_indices = sorted(index_lookup[key] for key in successor_keys) successor = atoms[successor_indices].copy() if not first_role and len(successor): successor[(successor[:, 0] == old[0]) & (successor[:, 1] == old[1])] = new tasks["successor_atomic"] = successor order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) excluded = {atomic_index, *successor_indices} replay = [i for i in order if i not in excluded][:replay_n] keep = [i for i in order if i not in excluded and i not in replay][:keep_n] unused = [i for i in range(len(atoms)) if i not in {atomic_index, *replay, *keep}] tasks["R_atomic"] = atoms[replay].copy() tasks["Kdev_atomic"] = atoms[keep].copy() tasks["U_atomic"] = atoms[unused].copy() if len(replay) != replay_n or len(keep) != keep_n: raise ValueError("Insufficient independent replay and calibration keep facts") return { "atomic_index": atomic_index, "group": group, "role": "first" if first_role else "second", "old_fact": old.tolist(), "new_fact": new.tolist(), "replay_indices": replay, "keep_indices": keep, "unused_indices": unused, "tasks": tasks, "original_d": original_d, }
def select_cases(world, n_per_group_role=2, calibration=False): """Graph-defined, largest affected-pool targets; no checkpoint-dependent selection.""" atoms = taught_atoms(world) chosen = [] groups = ["familiar"] if calibration else ["familiar", "strict"] for group in groups: rows = world[group + "_test"] for role in ["first", "second"]: counts = {} for row in rows: key = tuple(map(int, row[:2] if role == "first" else row[[2, 3]])) counts[key] = counts.get(key, 0) + 1 candidates = [i for i, atom in enumerate(atoms) if tuple(map(int, atom[:2])) in counts] candidates.sort(key=lambda i: (-counts[tuple(map(int, atoms[i, :2]))], tuple(atoms[i]))) for i in candidates[:n_per_group_role]: chosen.append(update_case(world, i, group)) if len(chosen) != len(groups) * 2 * n_per_group_role: raise ValueError("Not enough distinct graph-defined editor targets") return chosen
def serialize_case(case): return { key: {name: rows.tolist() for name, rows in value.items()} if key in ["tasks", "original_d"] else value for key, value in case.items() }
def answer_batch(rows, device): """Factual answer, punctuation and EOS only; random prefix targets are excluded.""" tokens, labels = pack_sentences(rows) first = 4 if rows.shape[1] == 3 else 6 positions = np.tile([first, first + 1, first + 2], (len(rows), 1)) selected = labels[np.arange(len(rows))[:, None], positions] np.testing.assert_array_equal( selected, np.c_[rows[:, -1], np.full(len(rows), 5), np.ones(len(rows), dtype=np.int64)] ) return tuple(torch.as_tensor(x, device=device) for x in [tokens, positions, selected])
def safe_generate(model, rows, device): if len(rows): return generate_rows(model, rows, device) return {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, { "generated": np.empty((0, 3), dtype=np.int64), "correct": np.empty(0, dtype=bool), "answer_nll": np.empty(0, dtype=np.float32), }
def editor(model, case, device, arm, lr, nodes=(0, 200)): """Independent local update, with parent KL reference and exact final tensor saved.""" if arm not in ["edit", "review"]: raise ValueError("Unknown editor arm") started = time.perf_counter() parent_hash = model_digest(model) edited = copy.deepcopy(model).eval() for name, parameter in edited.named_parameters(): parameter.requires_grad_(name == PARAMETER) parameter.grad = None before = {key: value.detach().clone() for key, value in edited.state_dict().items()} parameter = dict(edited.named_parameters())[PARAMETER] optimizer = torch.optim.Adam([parameter], lr=lr) target = answer_batch( np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]), device ) replay = answer_batch(case["tasks"]["R_atomic"], device) with torch.no_grad(): parent_log = model(replay[0], positions=replay[1]).log_softmax(-1).detach() parent_d = { name: safe_generate(model, rows, device)[1] for name, rows in case["original_d"].items() } parent_old_fact_ok = safe_generate(model, case["tasks"]["E_old"], device)[1]["correct"].all() parent_successors_ok = ( safe_generate(model, case["tasks"]["successor_atomic"], device)[1]["correct"].all() if case["role"] == "first" else True ) history, raw, step = [], {}, 0 for node in nodes: while step < node: optimizer.zero_grad(set_to_none=True) logits = edited(target[0], positions=target[1]) ce = F.cross_entropy(logits.flatten(0, 1), target[2].flatten()) current = edited(replay[0], positions=replay[1]).log_softmax(-1) kl = F.kl_div( current.flatten(0, 1), parent_log.flatten(0, 1), reduction="batchmean", log_target=True, ) loss = ce + kl loss.backward() optimizer.step() step += 1 metrics = {} for name, rows in case["tasks"].items(): metric, prediction = safe_generate(edited, rows, device) if name in case["original_d"]: original = case["original_d"][name] changed = rows[:, -1] != original[:, -1] parent_correct = parent_d[name]["correct"] eligible = changed & parent_correct & parent_old_fact_ok & parent_successors_ok pred = prediction["generated"] old = (pred[:, 0] == original[:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) metric.update( { "changed_n": int(changed.sum()), "parent_old_correct_n": int(parent_correct.sum()), "eligible_n": int(eligible.sum()), "changed_accuracy": float(prediction["correct"][changed].mean()) if changed.any() else None, "eligible_accuracy": float(prediction["correct"][eligible].mean()) if eligible.any() else None, "eligible_old_answer_accuracy": float(old[eligible].mean()) if eligible.any() else None, } ) raw[name + "_changed"] = changed raw[name + "_parent_correct"] = parent_correct raw[name + "_original_rows"] = original metrics[name] = metric raw.update({f"step{node}_{name}_{key}": value for key, value in prediction.items()}) history.append({"step": step, "metrics": metrics}) changed_tensors = [ key for key, value in edited.state_dict().items() if not torch.equal(value, before[key]) ] assert not set(changed_tensors) - {PARAMETER} assert model_digest(model) == parent_hash final = parameter.detach().cpu().clone() record = { "arm": arm, "lr": lr, "case": serialize_case(case), "history": history, "parent_model_sha256": parent_hash, "final_model_sha256": model_digest(edited), "changed_tensors": changed_tensors, "delta_l2": float((parameter - before[PARAMETER]).norm()), "seconds": time.perf_counter() - started, "parent_old_target_atomic_correct": bool(parent_old_fact_ok), "parent_new_successors_correct": bool(parent_successors_ok), } # Exact-tensor replay verifies every generated endpoint; no rounded delta reconstruction. reloaded = copy.deepcopy(model).eval() with torch.no_grad(): dict(reloaded.named_parameters())[PARAMETER].copy_(final.to(device)) assert model_digest(reloaded) == record["final_model_sha256"] for name, rows in case["tasks"].items(): _, prediction = safe_generate(reloaded, rows, device) for key, values in prediction.items(): reference = raw[f"step{nodes[-1]}_{name}_{key}"] if key == "answer_nll": np.testing.assert_allclose(values, reference, rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(values, reference) record["exact_weight_reload_passed"] = True return record, raw, final
def select_donors(world, rows): atoms = world["common_atomic"] lookup = {tuple(map(int, row[:2])): int(row[2]) for row in atoms} first = [(i, atom) for i, atom in enumerate(atoms) if 13 <= atom[1] <= 16] first.sort(key=lambda pair: tuple(pair[1])) records = {} for style in ["same_bridge", "different_bridge"]: indices, tails = [], [] for h, r1, bridge, r2, tail in rows: eligible = [ (i, atom) for i, atom in first if atom[1] == r1 and atom[0] != h and (int(atom[2]), int(r2)) in lookup and ( (atom[2] == bridge) if style == "same_bridge" else (atom[2] != bridge and lookup[int(atom[2]), int(r2)] != tail) ) ] indices.append(eligible[0][0] if eligible else -1) tails.append(lookup[int(eligible[0][1][2]), int(r2)] if eligible else -1) records[style] = {"indices": np.asarray(indices), "tails": np.asarray(tails)} return records
@torch.no_grad()def patched_generation(model, tokens, patch): generated = [] first_prob = None for step in range(3): logits, _ = traced_forward(model, tokens, patch) if step == 0: first_prob = logits[:, -1].softmax(-1) answer = logits[:, -1].argmax(-1) generated.append(answer.cpu().numpy()) tokens = torch.cat([tokens, answer[:, None]], dim=1) return np.stack(generated, axis=1), first_prob
@torch.no_grad()def trace(model, world, device, out): """Two fixed, causally reachable sites; donors contain only a first-hop prefix.""" model.eval() out = Path(out) records, raw = [], {} atoms = world["common_atomic"] atom_metric, atom_prediction = generate_rows(model, atoms, device) index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} for split in ["familiar", "strict"]: rows = world[split + "_test"] tokens = torch.as_tensor([composite_sentence(row)[:7] for row in rows], device=device) reference = model(tokens) logits, cache = traced_forward(model, tokens) torch.testing.assert_close(logits, reference, rtol=1e-5, atol=2e-6) assert torch.equal(logits.argmax(-1), reference.argmax(-1)) baseline_pred, baseline_prob = patched_generation(model, tokens, {}) raw[split + "_rows"] = rows raw[split + "_baseline_generated"] = baseline_pred for position in [3, 6]: state = cache["postresidual"][0, :, position] readout = F.linear(model.ln_final(state), model.token.weight) bridge = torch.as_tensor(rows[:, 2], device=device) rank = 1 + (readout > readout.gather(-1, bridge[:, None])).sum(-1) raw[f"{split}_bridge_rank_p{position}"] = rank.cpu().numpy() raw[split + "_attention"] = cache["attention_map"].cpu().numpy() for recipient, _donor_position in [(3, 3), (6, 4)]: for component in ["postresidual", "mlp_delta"]: self_patch = {(0, component, recipient): cache[component][0, :, recipient]} self_pred, self_prob = patched_generation(model, tokens, self_patch) np.testing.assert_array_equal(self_pred, baseline_pred) torch.testing.assert_close(self_prob, baseline_prob, rtol=1e-5, atol=2e-6) for style, donor in select_donors(world, rows).items(): valid = donor["indices"] >= 0 ids = np.flatnonzero(valid) if not len(ids): continue donor_rows = atoms[donor["indices"][valid]] donor_tokens = torch.as_tensor( [atomic_sentence(row)[:5] for row in donor_rows], device=device ) _, donor_cache = traced_forward(model, donor_tokens) expected = donor["tails"][valid] expected_tensor = torch.as_tensor(expected, device=device) premise = np.asarray( [ atom_prediction["correct"][index_lookup[int(row[0]), int(row[1])]] and atom_prediction["correct"][index_lookup[int(row[2]), int(row[3])]] and atom_prediction["correct"][int(donor_index)] and atom_prediction["correct"][index_lookup[int(donor_row[2]), int(row[3])]] for row, donor_row, donor_index in zip( rows[valid], donor_rows, donor["indices"][valid], strict=True ) ] ) raw[f"{split}_{style}_ids"] = ids raw[f"{split}_{style}_donor_rows"] = donor_rows raw[f"{split}_{style}_expected"] = expected for recipient, donor_position in [(3, 3), (6, 4)]: for component in ["postresidual", "mlp_delta"]: patch = { (0, component, recipient): donor_cache[component][0, :, donor_position] } pred, prob = patched_generation(model, tokens[valid], patch) correct = (pred[:, 0] == expected) & (pred[:, 1] == 5) & (pred[:, 2] == 1) base = baseline_pred[valid] base_correct = (base[:, 0] == expected) & (base[:, 1] == 5) & (base[:, 2] == 1) selected = torch.arange(len(ids), device=device) new_probability = prob[selected, expected_tensor].cpu().numpy() original_probability = ( baseline_prob[valid][selected, expected_tensor].cpu().numpy() ) name = f"{split}_{style}_p{recipient}_{component}" raw[name + "_generated"] = pred raw[name + "_gold_probability"] = new_probability raw[name + "_baseline_gold_probability"] = original_probability record = { "split": split, "style": style, "recipient_position": recipient, "donor_position": donor_position, "component": component, "n": len(ids), "pool_n": len(rows), "coverage": float(valid.mean()), "necessary_atoms_correct_n": int(premise.sum()), "baseline_target_accuracy": float(base_correct.mean()), "patched_target_accuracy": float(correct.mean()), "target_accuracy_delta_pp": 100 * float((correct.astype(float) - base_correct).mean()), "target_probability_delta": float( (new_probability - original_probability).mean() ), "conditional_target_accuracy": float(correct[premise].mean()) if premise.any() else None, } records.append(record) out.mkdir(parents=True, exist_ok=False) np.savez_compressed(out / "trace.npz", **raw) result = { "records": records, "traced_forward_and_self_patch_passed": True, "common_atomic": atom_metric, } write_json(out / "trace.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563"""Protocol replication of Wang et al.'s full-size two-hop grokking experiments.
The original GPT-2 vocabulary and configuration, answer/end-marker objective,random graph, edge-level split, merged sampling and unique-depth initializationare retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP areexplicit execution/numerical adaptations, checked against Hugging Face GPT-2."""
from __future__ import annotations
import hashlibimport jsonimport mathimport osimport timefrom pathlib import Path
import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast
from .bios_model import ModelConfig, matmul_flopsfrom .grok_depth import EpochStream, GraphStep, utc, write_json
ROOT = Path("results/grokking-reproduction-v1")ARTIFACTS = Path("docs/development-artifacts/grokking-reproduction-v1")SOURCE_FILES = [ "src/llm_memory_editability/grokking_reproduction.py", "scripts/run_grokking_reproduction.py", "tests/test_grokking_reproduction.py", "configs/grokking-reproduction-development-v1.json", "docs/development-artifacts/grokking-reproduction-v1/design.md",]
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def model_digest(model): h = hashlib.sha256() for name, tensor in model.state_dict().items(): h.update(name.encode()) h.update(tensor.detach().cpu().contiguous().numpy().tobytes()) return h.hexdigest()
def build_graph(seed, entities=2000, relations=200, degree=20, holdout=0.005): """Port the author's composition.ipynb; all tokens have shared graph roles.
The fixed permutation makes different phi supports nested while preserving each support's uniform marginal distribution. Mixed OOD chains are retained for diagnostic evaluation, never included in training. """ rng = np.random.RandomState(seed) atoms = np.empty((entities * degree, 3), dtype=np.int32) for h in range(entities): begin = h * degree atoms[begin : begin + degree, 0] = h atoms[begin : begin + degree, 1] = rng.choice(relations, degree, replace=False) atoms[begin : begin + degree, 2] = rng.randint(entities, size=degree) ood = np.zeros(len(atoms), dtype=bool) ood[rng.choice(len(atoms), round(len(atoms) * 0.05), replace=False)] = True first = np.repeat(np.arange(len(atoms)), degree) second = atoms[first, 2] * degree + np.tile(np.arange(degree), len(atoms)) chains = np.column_stack( [atoms[first, 0], atoms[first, 1], atoms[second, 1], atoms[second, 2]] ).astype(np.int32) kind = ood[first].astype(np.int8) * 2 + ood[second].astype(np.int8) ii = np.flatnonzero(kind == 0) held = rng.uniform(size=len(ii)) <= holdout train_ids = ii[~held] permutation = rng.permutation(len(train_ids)) return { "atoms": atoms, "ood": ood, "chains": chains, "first": first.astype(np.int32), "second": second.astype(np.int32), "kind": kind, "train_order": train_ids[permutation].astype(np.int32), "test_ii": ii[held].astype(np.int32), }
def audit_graph(world, degree): a, c = world["atoms"], world["chains"] first, second = world["first"], world["second"] assert np.array_equal(a[first, 2], a[second, 0]) assert np.array_equal(c[:, 0], a[first, 0]) assert np.array_equal(c[:, 1], a[first, 1]) assert np.array_equal(c[:, 2], a[second, 1]) assert np.array_equal(c[:, 3], a[second, 2]) assert len(np.unique(a[:, :2], axis=0)) == len(a) assert np.all(np.bincount(a[:, 0]) == degree) assert not np.intersect1d(world["train_order"], world["test_ii"]).size assert np.all(world["kind"][world["train_order"]] == 0) assert np.all(world["kind"][world["test_ii"]] == 0)
def prepare_data(config): path = ROOT / "data" path.mkdir(parents=True, exist_ok=True) if (path / "complete.json").exists(): complete = json.loads((path / "complete.json").read_text()) assert complete["world"] == config["world"] assert digest(path / "world.npz") == complete["world_sha256"] return complete world = build_graph(config["world"]) audit_graph(world, 20) np.savez_compressed(path / "world.npz", **world) rng = np.random.RandomState(config["evaluation_seed"])
def sample(indices): return rng.choice(indices, min(3000, len(indices)), replace=False)
min_support = round(min(s["phi"] for s in config["runs"]) * (~world["ood"]).sum()) panels = { "atomic_id": world["atoms"][sample(np.flatnonzero(~world["ood"]))], "atomic_ood": world["atoms"][sample(np.flatnonzero(world["ood"]))], "train_ii": world["chains"][sample(world["train_order"][:min_support])], "test_ii": world["chains"][sample(world["test_ii"])], "test_io": world["chains"][sample(np.flatnonzero(world["kind"] == 1))], "test_oi": world["chains"][sample(np.flatnonzero(world["kind"] == 2))], "test_oo": world["chains"][sample(np.flatnonzero(world["kind"] == 3))], } np.savez_compressed(path / "panels.npz", **panels) tokenizer = GPT2TokenizerFast.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) base = len(tokenizer) vocab = [f"<e_{i}>" for i in range(2000)] + [f"<r_{i}>" for i in range(200)] vocab += ["<mask>", "<sep>", "<a>", "</a>", "<q>", "</q>"] assert tokenizer.add_tokens(vocab) == len(vocab) assert tokenizer.convert_tokens_to_ids(vocab) == list(range(base, base + len(vocab))) tokenizer.pad_token = tokenizer.eos_token tokenizer.save_pretrained(path / "tokenizer") result = { "world": config["world"], "world_sha256": digest(path / "world.npz"), "panels_sha256": digest(path / "panels.npz"), "entities": 2000, "relations": 200, "degree": 20, "atomic_id": int((~world["ood"]).sum()), "atomic_ood": int(world["ood"].sum()), "candidate_train_ii": len(world["train_order"]), "full_test_ii": len(world["test_ii"]), "panels": {k: len(v) for k, v in panels.items()}, "base_vocabulary": base, "vocab_size": len(tokenizer), "entity_offset": base, "relation_offset": base + 2000, "end_marker": tokenizer.convert_tokens_to_ids("</a>"), "pad_token": tokenizer.pad_token_id, "created_utc": utc(), } write_json(path / "complete.json", result) write_json(ARTIFACTS / "data-audit.json", result) return result
def encode_rows(rows, metadata): """Only tail and </a> are targets; padding cannot influence earlier positions.""" rows = np.asarray(rows) x = np.full((len(rows), 4), metadata["pad_token"], dtype=np.int64) x[:, : rows.shape[1]] = rows x[:, 0] += metadata["entity_offset"] x[:, rows.shape[1] - 1] += metadata["entity_offset"] x[:, 1 : rows.shape[1] - 1] += metadata["relation_offset"] pos = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) labels = np.column_stack( [rows[:, -1] + metadata["entity_offset"], np.full(len(rows), metadata["end_marker"])] ) return x, pos, labels
def audit_support_roles(config): world = dict(np.load(ROOT / "data/world.npz")) panels = dict(np.load(ROOT / "data/panels.npz")) atoms = world["atoms"] lookup = np.full((2000, 200), -1, dtype=np.int32) lookup[atoms[:, 0], atoms[:, 1]] = np.arange(len(atoms)) results = [] for phi in sorted({s["phi"] for s in config["runs"]}): support = round(phi * (~world["ood"]).sum()) selected = world["train_order"][:support] first = np.bincount(world["first"][selected], minlength=len(atoms)) second = np.bincount(world["second"][selected], minlength=len(atoms)) seen_pairs = np.zeros((2000, 2000), dtype=bool) chains = world["chains"][selected] seen_pairs[chains[:, 0], chains[:, 3]] = True tasks = {} for name, rows in panels.items(): if rows.shape[1] != 4: continue e1 = lookup[rows[:, 0], rows[:, 1]] e2 = lookup[atoms[e1, 2], rows[:, 2]] assert np.all(e1 >= 0) and np.all(e2 >= 0) tasks[name] = { "n": len(rows), "first_fact_seen_in_first_role": float((first[e1] > 0).mean()), "second_fact_seen_in_second_role": float((second[e2] > 0).mean()), "both_seen_in_required_roles": float(((first[e1] > 0) & (second[e2] > 0)).mean()), "head_tail_pair_seen_in_training": float(seen_pairs[rows[:, 0], rows[:, 3]].mean()), } results.append( { "phi": phi, "support": support, "composition_fraction": support / (len(atoms) + support), "id_first_role_coverage": float((first[~world["ood"]] > 0).mean()), "id_second_role_coverage": float((second[~world["ood"]] > 0).mean()), "ood_first_role_count": int(first[world["ood"]].sum()), "ood_second_role_count": int(second[world["ood"]].sum()), "panels": tasks, } ) assert results[-1]["ood_first_role_count"] == results[-1]["ood_second_role_count"] == 0 write_json(ARTIFACTS / "support-role-audit.json", {"supports": results}) return results
class ReproductionGPT(nn.Module): """Native HF initialization and modules, with equivalent supervised readout."""
def __init__(self, config, repeats=1): super().__init__() self.config, self.repeats = config, repeats self.transformer = GPT2LMHeadModel(config).transformer
def forward(self, tokens, positions=None): cfg, t = self.config, self.transformer length = tokens.shape[1] x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device)) x = F.dropout(x, cfg.embd_pdrop, self.training) for _ in range(self.repeats): for block in t.h: z = block.ln_1(x) q, k, v = block.attn.c_attn(z).split(cfg.n_embd, dim=2) shape = (len(tokens), length, cfg.n_head, cfg.n_embd // cfg.n_head) q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v)) y = F.scaled_dot_product_attention( q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0 ) y = block.attn.c_proj(y.transpose(1, 2).reshape(len(tokens), length, cfg.n_embd)) x = x + F.dropout(y, cfg.resid_pdrop, self.training) x = x + block.mlp(block.ln_2(x)) x = t.ln_f(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] return F.linear(x, t.wte.weight)
def construct(spec, metadata, device): torch.manual_seed(spec["initialization"]) cfg = GPT2Config.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) cfg.vocab_size = metadata["vocab_size"] cfg.n_layer = spec["unique_layers"] cfg.use_cache = False return ReproductionGPT(cfg, spec["repeats"]).to(device)
def optimizer_for(model, lr, decay): params = list(model.named_parameters()) return torch.optim.AdamW( [ { "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])], "weight_decay": decay, }, { "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])], "weight_decay": 0.0, }, ], lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=True, capturable=True, )
class ReproductionStep(GraphStep): def eager(self): self.optimizer.zero_grad(set_to_none=False) x, positions, labels = (part[self.index] for part in self.table) with torch.autocast("cuda", dtype=torch.bfloat16): logits = self.model(x, positions) loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
class MergedBatchStream(EpochStream): """Match DataLoader's final partial batch using loss-masked graph padding."""
def batch(self, batch_size): if not len(self.remaining): self.remaining = self.rng.permutation(self.size) count = min(batch_size, len(self.remaining)) result = np.full(batch_size, self.size, dtype=np.int64) result[:count] = self.remaining[:count] self.remaining = self.remaining[count:] return result, count
@torch.no_grad()def evaluate_rows(model, rows, metadata, device, batch_size=256): model.eval() packed = encode_rows(rows, metadata) answers, stops, losses = [], [], [] for start in range(0, len(rows), batch_size): x, pos, labels = [ torch.as_tensor(p[start : start + batch_size], device=device) for p in packed ] with torch.autocast("cuda", dtype=torch.bfloat16): logits = model(x, pos) nll = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") answer = logits[:, 0].argmax(-1) x[torch.arange(len(x), device=device), pos[:, 1]] = answer stop = model(x, pos)[:, 1].argmax(-1) answers.append(answer.cpu().numpy()) stops.append(stop.cpu().numpy()) losses.append(nll.view(-1, 2).float().cpu().numpy()) model.train() answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) correct = answer == rows[:, -1] + metadata["entity_offset"] return { "n": len(rows), "answer_accuracy": float(correct.mean()), "accuracy": float((correct & (stop == metadata["end_marker"])).mean()), "answer_nll": float(nll[:, 0].mean()), "nll": float(nll.mean()), }, {"answer": answer, "stop": stop, "nll": nll, "rows": rows}
def learning_rate(spec, step): # HF's warmup schedule starts the first optimizer update at zero LR. return spec["lr"] * min((step - 1) / spec["warmup"], 1.0)
def save_checkpoint(path, model, optimizer, stream, counts, step, spec, training_seconds): tmp = path.with_suffix(".tmp") torch.save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "stream": stream.state_dict(), "counts": counts, "step": step, "spec": spec, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(), "training_seconds": training_seconds, }, tmp, ) tmp.replace(path)
def train_run(config, spec, gpu): torch.set_num_threads(4) if torch.get_num_interop_threads() != 1: torch.set_num_interop_threads(1) torch.cuda.set_device(gpu) torch.backends.cuda.matmul.allow_tf32 = True device = torch.device(f"cuda:{gpu}") out = ROOT / "development" / spec["name"] out.mkdir(parents=True, exist_ok=True) if (out / "complete.json").exists(): return metadata = json.loads((ROOT / "data/complete.json").read_text()) assert digest(ROOT / "data/world.npz") == metadata["world_sha256"] assert digest(ROOT / "data/panels.npz") == metadata["panels_sha256"] world = dict(np.load(ROOT / "data/world.npz")) support = round(spec["phi"] * metadata["atomic_id"]) selected = world["train_order"][:support] assert len(selected) == support atomic = encode_rows(world["atoms"], metadata) composite = encode_rows(world["chains"][selected], metadata) padding = ( np.full((1, 4), metadata["pad_token"], dtype=np.int64), np.array([[2, 3]], dtype=np.int64), np.array([[-100, -100]], dtype=np.int64), ) table = tuple( torch.as_tensor(np.concatenate([a, b, p]), device=device) for a, b, p in zip(atomic, composite, padding, strict=True) ) del atomic, composite model = construct(spec, metadata, device) initial_hash = model_digest(model) lr = torch.tensor(0.0, device=device) optimizer = optimizer_for(model, lr, spec["weight_decay"]) stream = MergedBatchStream(len(table[0]) - 1, spec["stream_seed"]) counts = np.zeros(len(table[0]) - 1, dtype=np.int64) step, training_seconds = 0, 0.0 latest = out / "latest.pt" rng = None if latest.exists(): saved = torch.load(latest, map_location=device, weights_only=False) assert saved["spec"] == spec model.load_state_dict(saved["model"]) optimizer.load_state_dict(saved["optimizer"]) # load_state_dict can replace group LR objects; refill the object the optimizer uses. lr = optimizer.param_groups[0]["lr"] for group in optimizer.param_groups: group["lr"] = lr stream.load_state_dict(saved["stream"]) counts, step = saved["counts"], saved["step"] training_seconds = saved["training_seconds"] rng = (saved["cpu_rng"].cpu(), saved["cuda_rng"].cpu()) del saved if rng is not None: torch.set_rng_state(rng[0]) torch.cuda.set_rng_state(rng[1]) model.train() graph = ReproductionStep(model, optimizer, table, spec["batch_size"]) panels = dict(np.load(ROOT / "data/panels.npz")) learning_path = out / "learning.json" history = json.loads(learning_path.read_text()) if learning_path.exists() else [] history = [r for r in history if r["step"] <= step] started = time.perf_counter() parameters = sum(p.numel() for p in model.parameters()) flop_step = matmul_flops( ModelConfig( metadata["vocab_size"], model.config.n_embd, model.config.n_layer * model.repeats, model.config.n_head, 1024, ), spec["batch_size"], sequence=4, output_positions=2, ) write_json( out / "run.json", { "spec": spec, "world_sha256": metadata["world_sha256"], "initial_model_sha256": initial_hash, "parameters": parameters, "atomic_examples": len(world["atoms"]), "composition_examples": support, "vocab_size": metadata["vocab_size"], "gpu": gpu, "gpu_name": torch.cuda.get_device_name(gpu), "started_utc": utc(), "dtype": "bf16 AMP with float32 parameters/Adam state", "pid": os.getpid(), "resumed_step": step, }, )
def measure(): metrics = {} for name, panel in panels.items(): metrics[name], pred = evaluate_rows(model, panel, metadata, device) np.savez_compressed(out / f"predictions-{step:07d}-{name}.npz", **pred) record = { "step": step, "metrics": metrics, "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "created_utc": utc(), "examples": int(counts.sum()), "supervised_tokens": int(counts.sum()) * 2, "executed_input_tokens": step * spec["batch_size"] * 4, "estimated_matmul_training_flops": step * flop_step, "composition_epochs": float(counts[len(world["atoms"]) :].sum() / support), "atomic_epochs": float(counts[: len(world["atoms"])].sum() / len(world["atoms"])), } history.append(record) write_json(learning_path, history) write_json( out / "status.json", { "state": "running", "step": step, "budget": spec["steps"], "training_seconds": training_seconds, "train_ii": metrics["train_ii"]["accuracy"], "test_ii": metrics["test_ii"]["accuracy"], "test_oo": metrics["test_oo"]["accuracy"], "updated_utc": utc(), }, ) print( json.dumps( { "name": spec["name"], "step": step, "train": metrics["train_ii"]["accuracy"], "id": metrics["test_ii"]["accuracy"], "oo": metrics["test_oo"]["accuracy"], } ), flush=True, )
def checkpoint(): save_checkpoint(latest, model, optimizer, stream, counts, step, spec, training_seconds) retained = out / f"checkpoint-{step:07d}.pt" torch.save({"model": model.state_dict(), "spec": spec, "step": step}, retained) np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts, selected=selected)
if not history or history[-1]["step"] != step: measure() if step == 0 and 0 in config["checkpoint_nodes"]: checkpoint() for end in [n for n in config["evaluation_nodes"] if n > step]: torch.cuda.synchronize() segment = time.perf_counter() while step < end: n = min(128, end - step) indices = np.stack([stream.batch(spec["batch_size"])[0] for _ in range(n)]) counts += np.bincount(indices.ravel(), minlength=len(counts) + 1)[: len(counts)] indices = torch.as_tensor(indices, device=device) for i in range(n): lr.fill_(learning_rate(spec, step + i + 1)) loss = graph(indices[i]) step += n torch.cuda.synchronize() training_seconds += time.perf_counter() - segment loss_value = float(loss) if not math.isfinite(loss_value) or not math.isfinite(float(graph.grad_norm)): raise FloatingPointError(f"Nonfinite loss/gradient at {step}") measure() if step in config["checkpoint_nodes"]: checkpoint() assert step == spec["steps"] epoch_steps = math.ceil(len(counts) / spec["batch_size"]) full_epochs, remainder = divmod(step, epoch_steps) expected_examples = full_epochs * len(counts) + remainder * spec["batch_size"] assert counts.sum() == expected_examples assert counts.max() - counts.min() <= 1 # Full endpoint evaluation complements the original fixed 3k training panels. full = {} for name, data in { "atomic_all": world["atoms"], "train_ii_all": world["chains"][selected], }.items(): full[name], pred = evaluate_rows(model, data, metadata, device) np.savez_compressed(out / f"endpoint-{name}.npz", **pred) final = { "state": "complete", "step": step, "full_endpoint": full, "parameters": parameters, "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "estimated_matmul_training_flops": step * flop_step, "completed_utc": utc(), "final_checkpoint_sha256": digest(out / f"checkpoint-{step:07d}.pt"), "model_sha256": model_digest(model), } write_json(out / "complete.json", final) write_json(out / "status.json", final)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396"""CounterFact true-label data, explicit audit decisions and indivisible subject pools."""
from __future__ import annotations
import hashlibimport reimport unicodedatafrom collections import Counter, defaultdict
import numpy as np
from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, sha256, write_json
TEMPLATE = "Complete the statement with the missing answer only.\nStatement: {}\nAnswer:"
def normalize(text): return " ".join(unicodedata.normalize("NFKC", text).split()).casefold()
def normalize_answer(text): text = normalize(text) while text and unicodedata.category(text[-1]).startswith("P"): text = text[:-1].rstrip() return text
def score_answer(prediction, aliases): lines = [x.strip() for x in prediction.splitlines() if x.strip()] first = lines[0] if lines else "" return int(normalize_answer(first) in {normalize_answer(x) for x in aliases})
def encode_answer(tokenizer, prompt, answer): """Tokenize the complete string once; offset overlap includes leading answer space.""" suffix = " " + answer text = prompt + suffix encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True) ids, offsets = encoded["input_ids"], encoded["offset_mapping"] start = len(prompt) mask = [int(end > start) for begin, end in offsets] if any(begin < start < end for begin, end in offsets): raise ValueError("A token straddles the prompt/answer boundary") answer_start = mask.index(1) if ids[:answer_start] != tokenizer(prompt, add_special_tokens=False)["input_ids"]: raise ValueError("Prompt tokenization changes at the answer boundary") assert not any(mask[:answer_start]) and all(mask[answer_start:]) return { "input_ids": ids + [tokenizer.eos_token_id], "loss_mask": mask + [1], "answer_start": answer_start, "answer_tokens": sum(mask), "prompt_tokens": answer_start, }
def stable_hash(text): return hashlib.sha256(text.encode()).hexdigest()
def clean_candidates(tokenizer): cfg = config()["data"] raw_path = DATA / "source/counterfact.json" raw = read_json(raw_path) audit, candidates, seen = [], [], {} conflicting = set() # Near-identical punctuation/accent variants are conservatively quarantined; # normalized identical subjects already share a group. subjects = defaultdict(set) for row in raw: name = normalize(row["requested_rewrite"]["subject"]) key = "".join(c for c in unicodedata.normalize("NFKD", name) if c.isalnum()) subjects[key].add(name) ambiguous = set().union(*(v for v in subjects.values() if len(v) > 1)) for row in raw: r = row["requested_rewrite"] if r["relation_id"] not in cfg["relations"]: continue subject = " ".join(unicodedata.normalize("NFKC", r["subject"]).split()) group = normalize(subject) answer = r["target_true"]["str"].strip() views = [r["prompt"].format(r["subject"])] + row["paraphrase_prompts"][:2] views = [" ".join(unicodedata.normalize("NFKC", p).split()) for p in views] reasons = [] decision = "include" if len(views) != 3 or len(set(map(normalize, views))) != 3: reasons.append("missing_or_duplicate_views") if any( re.search(r"(?<!\w)" + re.escape(normalize(answer)) + r"(?!\w)", normalize(p)) for p in views ): reasons.append("answer_leakage_in_prompt_or_subject") if any(normalize(subject) not in normalize(p) for p in views): reasons.append("subject_missing_from_view") if group in ambiguous: reasons.append("possible_subject_alias") decision = "review" # Some source paraphrases ask nationality, not native language. if r["relation_id"] == "P103" and any(p.endswith(", a native") for p in views): reasons.append("native_is_ambiguous_between_language_and_origin") decision = "review" # Manufacturer names truncated to a country or a non-unique first word. if r["relation_id"] in {"P176", "P178"} and answer in {"Iran", "Douglas", "Square"}: reasons.append("source_answer_name_requires_entity_review") decision = "review" encoded = [] try: encoded = [encode_answer(tokenizer, TEMPLATE.format(p), answer) for p in views] if any(x["prompt_tokens"] > cfg["prompt_max_tokens"] for x in encoded): reasons.append("prompt_over_limit") if any(x["answer_tokens"] > cfg["answer_max_tokens"] for x in encoded): reasons.append("answer_over_limit") except ValueError as e: reasons.append(str(e)) key = (group, r["relation_id"]) if key in seen: previous = seen[key] if previous["target_id"] == r["target_true"]["id"]: previous["source_ids"].append(row["case_id"]) reasons.append("merged_subject_relation_duplicate") else: reasons.append("conflicting_subject_relation_targets") decision = "review" conflicting.add(key) if reasons and decision == "include": decision = "exclude" record = { "case_id": row["case_id"], "source_ids": [row["case_id"]], "subject": subject, "subject_group": group, "relation_id": r["relation_id"], "target_id": r["target_true"]["id"], "answer": answer, "target_new_source_only": r["target_new"], "views": views, "encoded": encoded, } audit.append( { "case_id": row["case_id"], "decision": decision, "reasons": reasons, "audit_type": "programmatic", "subject_group": group, } ) if decision == "include": candidates.append(record) seen[key] = record # Conflicting labels disqualify every side of a conflict, including the first row. conflict_ids = { r["case_id"] for r in candidates if (r["subject_group"], r["relation_id"]) in conflicting } for entry in audit: if entry["case_id"] in conflict_ids: entry["decision"] = "review" entry["reasons"].append("conflicting_subject_relation_targets") candidates = [r for r in candidates if r["case_id"] not in conflict_ids] prompt_owners = defaultdict(set) for record in candidates: for prompt in record["views"]: prompt_owners[normalize(prompt)].add(record["subject_group"]) collision_ids = { r["case_id"] for r in candidates if any(len(prompt_owners[normalize(p)]) > 1 for p in r["views"]) } for entry in audit: if entry["case_id"] in collision_ids: entry["decision"] = "review" entry["reasons"].append("cross_subject_prompt_collision") candidates = [r for r in candidates if r["case_id"] not in collision_ids] # Each pool gets a disjoint candidate reserve before any baseline outcome is observed. # Extra keep reserve accounts for its required pre-existing exact generation success. pool_weights = {k: n * (3 if k.endswith("keep") else 1) for k, n in cfg["pools"].items()} total_weight = sum(pool_weights.values()) by_subject = defaultdict(list) for r in candidates: by_subject[r["subject_group"]].append(r) stratified = defaultdict(list) for group, rows in by_subject.items(): stratified[min(r["relation_id"] for r in rows)].append(group) rng = np.random.default_rng(cfg["split_seed"]) for _relation, groups in sorted(stratified.items()): groups.sort(key=stable_hash) rng.shuffle(groups) cumulative = 0.0 start = 0 for pool, weight in pool_weights.items(): cumulative += weight / total_weight end = round(cumulative * len(groups)) for group in groups[start:end]: for record in by_subject[group]: record["candidate_pool"] = pool start = end write_json(DATA / "candidates.json", candidates) write_json(ARTIFACTS / "programmatic-audit.json", audit) write_json( ARTIFACTS / "subject-alias-audit.json", { "method": "NFKC/casefold grouping; punctuation/accent variants quarantined", "limitations": "No claim of exhaustive real-world entity resolution", "review_groups": [sorted(v) for v in subjects.values() if len(v) > 1], }, ) write_json( ARTIFACTS / "preparation.json", { "time": now(), "raw_count": len(raw), "source_sha256": sha256(raw_path), "candidate_count": len(candidates), "decisions": dict(Counter(x["decision"] for x in audit)), "reasons": dict(Counter(y for x in audit for y in x["reasons"])), "candidate_pools": dict(Counter(x["candidate_pool"] for x in candidates)), "candidate_sha256": sha256(DATA / "candidates.json"), "status": "awaiting_individual_semantic_audit_and_baseline", "source_license": ( "CounterFact source snapshot; upstream ROME repository MIT; " "dataset-specific license not asserted" ), }, ) return candidates
def balanced_order(records, seed): rng = np.random.default_rng(seed) groups = defaultdict(list) for record in sorted(records, key=lambda r: r["case_id"]): groups[record["relation_id"]].append(record) for items in groups.values(): rng.shuffle(items) result = [] while any(groups.values()): for relation in sorted(groups): if groups[relation]: result.append(groups[relation].pop()) return result
def semantic_audit(): """Apply explicitly reviewed predicate rules; retain per-row evidence and limitations.
This is a reproducible semantic rule audit, not a claim that a human or another model independently reviewed every source fact. Benchmark truth is assumed. """ candidates = read_json(DATA / "candidates.json") result = [] for record in candidates: issues, evidence = [], [] subject = normalize(record["subject"]) relation = record["relation_id"] for view in record["views"]: text = normalize(view) start = text.rfind(subject) suffix = text[start + len(subject) :].strip() prefix = text[:start] evidence.append({"predicate_suffix": suffix, "relation_prefix": prefix[-64:]}) if relation == "P19" and suffix != "was born in": issues.append("origin_or_native_place_does_not_uniquely_mean_birthplace") if relation == "P103" and (suffix in {"spoke the language", ", speaker of"}): issues.append("spoken_language_does_not_uniquely_mean_mother_tongue") if ( relation == "P103" and suffix == "is" and not any( prefix.endswith(p) for p in ["the mother tongue of ", "the native language of "] ) ): issues.append("missing_native_language_relation") if relation == "P176" and "developed by" in suffix: issues.append("developer_is_not_necessarily_manufacturer") if relation == "P178" and "manufactured by" in suffix: issues.append("manufacturer_is_not_necessarily_developer") if ( relation in {"P364", "P407"} and suffix in {"is", "was"} and not any( prefix.endswith(p) for p in ["the language of ", "the original language of "] ) ): issues.append("missing_language_relation") result.append( { "case_id": record["case_id"], "decision": "review" if issues else "include", "reasons": sorted(set(issues)), "view_evidence": evidence, "audit_type": "model_authored_semantic_rules_applied_programmatically", "truth_status": "CounterFact original label; no independent fact verification", } ) write_json(ARTIFACTS / "semantic-audit.json", result) write_json( ARTIFACTS / "semantic-audit-method.json", { "time": now(), "status": "conservative_template_semantics_audit", "decisions": dict(Counter(r["decision"] for r in result)), "limitations": [ "Real-world truths and all entity aliases are not independently verified", "Creator/product/origin formulations use source benchmark semantics", "Model-authored rule audit; independent human review not performed", ], "primary_subset": "Only all-three-view records passing these conservative rules", "review_pool": "Excluded from all fitting and evaluation; never auto-promoted", }, ) return result
def lock_data(): """No training may consume unaudited rows or an outcome-adapted subject split.""" cfg = config()["data"] candidates = read_json(DATA / "candidates.json") semantic = {r["case_id"]: r for r in read_json(ARTIFACTS / "semantic-audit.json")} baseline = {r["case_id"]: r for r in read_json(DATA / "baseline.json")} pools, coverage = {}, {} for name, count in cfg["pools"].items(): available = [ r for r in candidates if r["candidate_pool"] == name and semantic.get(r["case_id"], {}).get("decision") == "include" and r["case_id"] in baseline ] if name.endswith("keep"): available = [r for r in available if baseline[r["case_id"]]["views"][0]["answer_em"]] ordered = balanced_order(available, cfg["split_seed"]) if name.startswith(("B_", "C_")):
def needs_learning(r): v = baseline[r["case_id"]]["views"] return not v[0]["answer_em"] and not all(x["answer_em"] for x in v[1:])
ordered = [r for r in ordered if needs_learning(r)] + [ r for r in ordered if not needs_learning(r) ] unit = cfg["episode_size"].get(name, 8) actual = min(count, len(ordered) // unit * unit) if actual < unit: raise ValueError(f"{name} has fewer than one complete batch/episode: {len(ordered)}") pools[name] = ordered[:actual] coverage[name] = { "planned": count, "available": len(ordered), "actual": actual, "relations": dict(Counter(r["relation_id"] for r in ordered[:actual])), } group_sets = {k: {r["subject_group"] for r in rows} for k, rows in pools.items()} names = list(pools) for i, a in enumerate(names): for b in names[i + 1 :]: assert not group_sets[a] & group_sets[b], (a, b) aliases = defaultdict(set) for rows in pools.values(): for r in rows: aliases[r["target_id"]].add(r["answer"]) for rows in pools.values(): for r in rows: r["aliases"] = sorted(aliases[r["target_id"]]) r["baseline"] = baseline[r["case_id"]] episodes = { name: [ [r["case_id"] for r in rows[i : i + cfg["episode_size"][name]]] for i in range(0, len(rows), cfg["episode_size"][name]) ] for name, rows in pools.items() if name in cfg["episode_size"] } write_json(DATA / "pools.json", pools) write_json(DATA / "episodes.json", episodes) write_json( ARTIFACTS / "data-lock.json", { "time": now(), "coverage": coverage, "subject_disjoint": True, "files": { p: sha256(DATA / p) for p in [ "candidates.json", "pools.json", "episodes.json", "baseline.json", "text.json", ] }, "semantic_audit_sha256": sha256(ARTIFACTS / "semantic-audit.json"), "revision": "Full-episode coverage reduction before model learning, where needed", "status": "locked", }, ) return coverage123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Fixed-content worlds and conservative full-entity answer parsing."""
from __future__ import annotations
import hashlibimport reimport unicodedatafrom collections import defaultdict
import numpy as np
from .hebbian_future import ROOT, chain_world
CONFIG = ROOT / "configs/hebbian-future-v2.json"ART = ROOT / "docs/development-artifacts/hebbian-future-v2"DATA = ROOT / "data/hebbian-future-v2"RESULTS = ROOT / "results/hebbian-future-v2"
def stable(value): return hashlib.sha256(str(value).encode()).hexdigest()
def fixed_world(world, rho, cfg): """Change only nonfocal home values as rho changes; focal wrong values stay fixed.""" w = chain_world(world, rho, cfg) rng = np.random.default_rng(world + 918273) people = rng.permutation(cfg["people"]).reshape(cfg["organizations"], 8) hq = rng.permutation(np.arange(cfg["organizations"]) % cfg["cities"]) city_order = rng.permutation(cfg["cities"]) matches = int(rho * 4) for group, persons in enumerate(people): for split in range(2): selected = persons[split * 4 : split * 4 + 4] # Offset of slot j is j at EVERY rho until made coherent. Slot 3 # is always the same competing city, in both train and held-out. offsets = np.arange(4) offsets[:matches] = 0 w["home"][selected] = city_order[(hq[group] + offsets) % 4] w["home_y"] = w["city_start"] + w["home"] return w
def normalize(text): return " ".join(unicodedata.normalize("NFKC", text).casefold().split())
def inventory_from_facts(facts): inventory = defaultdict(dict) for fact in facts: values = inventory[fact["relation_id"]] item = values.setdefault(fact["target_id"], {"label": fact["answer"], "aliases": []}) item["aliases"] = sorted(set(item["aliases"] + fact.get("aliases", []) + [fact["answer"]])) return dict(inventory)
def parse_entity(text, inventory): """Read a leading complete alias, abstaining on collisions/negation/lists.
Plain completion makes a leading answer meaningful. The parser does not convert every nonmatch into factual error. No model-assisted grading. """ text = normalize(text).lstrip(" \"'`“”‘’([{:") if not text: return {"status": "unrecognized", "entity": None} if re.match(r"(?:not|no|neither|unknown|i don't|i do not)\b", text): return {"status": "unrecognized", "entity": None} matches = [] for entity, item in inventory.items(): for alias in item["aliases"]: a = normalize(alias) if text.startswith(a) and (len(text) == len(a) or not text[len(a)].isalnum()): matches.append((len(a), entity)) if not matches: return {"status": "unrecognized", "entity": None} length = max(n for n, _ in matches) entities = {entity for n, entity in matches if n == length} if len(entities) != 1: return {"status": "ambiguous", "entity": None} suffix = text[length:].lstrip() if re.match(r"(?:and|or|/|,?\s*not)\b", suffix): return {"status": "ambiguous", "entity": None} return {"status": "recognized", "entity": next(iter(entities))}
def candidate_set(fact, inventory, seed): items = inventory[fact["relation_id"]] own_aliases = {normalize(a) for a in items[fact["target_id"]]["aliases"]} ordered = sorted(items, key=lambda x: stable(f"{seed}:{fact['case_id']}:{x}")) selected = [fact["target_id"]] aliases = set(own_aliases) for entity in ordered: other = {normalize(a) for a in items[entity]["aliases"]} if entity in selected or aliases.intersection(other): continue selected.append(entity) aliases.update(other) if len(selected) == 4: break if len(selected) != 4: raise ValueError("Need four distinct, unambiguous candidates") # Correct position varies independently of model outputs. return sorted(selected, key=lambda x: stable(f"position:{seed}:{fact['case_id']}:{x}"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026."""
from __future__ import annotations
import hashlibimport jsonfrom pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[2]CONFIG = ROOT / "configs/hebbian-future-v1.json"ART = ROOT / "docs/development-artifacts/hebbian-future-v1"DATA = ROOT / "data/hebbian-future-v1"RESULTS = ROOT / "results/hebbian-future-v1"
def read(path): return json.loads(Path(path).read_text())
def write(path, obj): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n") temporary.replace(path)
def digest(path): h = hashlib.sha256() with Path(path).open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): h.update(block) return h.hexdigest()
def unit(x): x = np.asarray(x, dtype=np.float64) return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12)
def chain_world(world, correlation, cfg): """Match marginals, subjects, memberships and query exposure across correlations.
Eight people per organization: four combination-trained, four held out. Within EACH split and organization exactly rho*4 have home==HQ. Other home cities cycle identically across the balanced HQ city groups, keeping both training/held-out home-city histograms uniform. ID permutations are shared. """ n, groups, cities = (cfg[x] for x in ("people", "organizations", "cities")) assert n == groups * 8 and groups % cities == 0 rng = np.random.default_rng(world + 918273) people = rng.permutation(n).reshape(groups, 8) headquarters = rng.permutation(np.arange(groups) % cities) city_order = rng.permutation(cities) membership = np.empty(n, dtype=int) home = np.empty(n, dtype=int) train = np.zeros(n, dtype=bool) common_conflict = np.zeros(n, dtype=bool) matches = int(correlation * 4) for group, persons in enumerate(people): membership[persons] = group for split in range(2): subset = persons[split * 4 : split * 4 + 4] common_conflict[subset[-1]] = True offsets = np.r_[np.zeros(matches, dtype=int), 1 + np.arange(4 - matches) % 3] home[subset] = city_order[(headquarters[group] + offsets) % cities] if split == 0: train[subset] = True headquarters = city_order[headquarters] # Shared vocabulary and query positions; labels are next-token + EOS. person_start, group_start, city_start = 10, 10 + n, 10 + n + groups vocab = city_start + cities member = np.stack( [np.ones(n, int), person_start + np.arange(n), np.full(n, 3), np.full(n, 2)], axis=1 ) root = np.stack( [ np.ones(groups, int), group_start + np.arange(groups), np.full(groups, 4), np.full(groups, 2), ], axis=1, ) resident = member.copy() resident[:, 2] = 5 composite = member.copy() composite[:, 2] = 6 return { "world": world, "correlation": correlation, "vocab": vocab, "membership": membership, "home": home, "headquarters": headquarters, "train_people": train, "common_conflict": common_conflict, "member_x": member, "root_x": root, "home_x": resident, "composite_x": composite, "member_y": group_start + membership, "root_y": city_start + headquarters, "home_y": city_start + home, "composite_y": city_start + headquarters[membership], "group_start": group_start, "city_start": city_start, }
def training_arrays(world): mask = world["train_people"] x = np.concatenate( [world[k + "_x"] for k in ("member", "root", "home")] + [world["composite_x"][mask]] ) y = np.concatenate( [world[k + "_y"] for k in ("member", "root", "home")] + [world["composite_y"][mask]] ) return x, y
def ridge_predict(train_x, train_y, test_x, penalty=10.0): """Fixed ridge linear probability model; statistics fitted on dev only.""" mean, scale = train_x.mean(0), np.maximum(train_x.std(0), 1e-8) a = np.c_[np.ones(len(train_x)), (train_x - mean) / scale] b = np.c_[np.ones(len(test_x)), (test_x - mean) / scale] reg = np.eye(a.shape[1]) * penalty reg[0, 0] = 0 beta = np.linalg.solve(a.T @ a + reg, a.T @ train_y) return np.clip(b @ beta, 0, 1)
def auc(y, scores): positive, negative = np.asarray(scores)[y == 1], np.asarray(scores)[y == 0] if not len(positive) or not len(negative): return None return float( (positive[:, None] > negative).mean() + 0.5 * (positive[:, None] == negative).mean() )
def bootstrap_mean(values, seed, repeats=1000): values = np.asarray(values) rng = np.random.default_rng(seed) means = values[rng.integers(len(values), size=(repeats, len(values)))].mean(1) return [float(x) for x in np.quantile(means, [0.025, 0.975])]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566"""Paired CE/MSE memory interfaces on the released synthetic recall task.
The official implementation supplies memory fitting, the reader, and batches.This adapter fixes budgets and seeds, removes the future answer from inputs,and records a complete crossing without selecting on the replacement mapping."""
from __future__ import annotations
import hashlibimport importlib.metadataimport jsonimport platformimport sysimport timefrom dataclasses import asdictfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as F
ROOT = Path(__file__).resolve().parents[2]DEFAULT_SPEC = { "num_facts": 128, "d_model": 64, "hidden_dim": 256, "junk_len": 9, "junk_vocab_size": 9, "batch_size": 256, "mlp_epochs": 10000, "mlp_lr": 0.001, "mlp_min_lr": 1e-6, "mlp_cutoff": -1.0, "mlp_activation": "swish", "mlp_bias": True, "reader_steps": 4000, "reader_lr": 2e-4, "reader_weight_decay": 0.1, "eval_every": 1000, "eval_repeats": 8, "cpu_threads": 1, "source_path": "data/hebbian-interface-v1/source",}
def _source(spec): source = ROOT / spec["source_path"] / "src" if str(source) not in sys.path: sys.path.insert(0, str(source))
def tensor_hash(tensors): """Hash names, shapes, dtypes and raw values, independently of serialization.""" digest = hashlib.sha256() for name, value in sorted(tensors.items()): tensor = value.detach().cpu().contiguous() digest.update(f"{name}:{tuple(tensor.shape)}:{tensor.dtype}".encode()) digest.update(tensor.numpy().tobytes()) return digest.hexdigest()
def _state(model, *, non_mlp=False, frozen=False): return { name: value for name, value in model.named_parameters() if (not non_mlp or ".mlp." not in name) and (not frozen or not value.requires_grad) }
def _memory_config(spec, loss, device): from hebbian.mlp_core.mlp_gd import GDMLPConfig from hebbian.mlp_core.task import SharedConstructionConfig
shared = SharedConstructionConfig( build_dtype=torch.float32, final_dtype=torch.float32, device=str(device), verbose=False, ) shared.mlp_config.activation.activation = spec["mlp_activation"] return GDMLPConfig( shared=shared, m=spec["hidden_dim"], bias=spec["mlp_bias"], num_epochs=spec["mlp_epochs"], lr=spec["mlp_lr"], min_lr=spec["mlp_min_lr"], cutoff=spec["mlp_cutoff"], loss_fn=loss, batch_size=None, eval_every=spec["eval_every"], )
def _new_memory(spec, device): from hebbian.mlp_core.mlp_gd import _create_gd_mlp
return _create_gd_mlp(spec["d_model"], spec["hidden_dim"], _memory_config(spec, "ce", device))
def make_config(spec, seed, device): """The fixed SSFR architecture; memory and optimizer numbers come from spec.""" _source(spec) from hebbian.transformer.config import AssociativeRecallConfig
config = AssociativeRecallConfig() dc, tc = config.dataset_config, config.train_config dc.num_facts = spec["num_facts"] dc.junk_vocab_size = spec["junk_vocab_size"] dc.min_seq_length = dc.max_seq_length = spec["junk_len"] dc.custom_finalize() tc.device, tc.dtype, tc.seed = str(device), torch.float32, seed tc.embeddings_config.d_model = spec["d_model"] tc.embeddings_config.tie_embeddings = True tc.mlp_method, tc.mlp_hidden_dim = "gd", spec["hidden_dim"] tc.batch_size, tc.steps_per_dataset = spec["batch_size"], spec["reader_steps"] arch = tc.transformer_config arch.n_layers = arch.n_head = 1 arch.use_identity_mlp = True arch.mlp_residual = arch.attn_residual = False arch.use_rope, arch.no_positional_encoding = False, True arch.freeze_value_dense_identity = True arch.mlp_norm_type = arch.lm_head_norm_type = "unit_rmsnorm" arch.attn_norm_type, arch.bias = "rmsnorm", False return config
def make_batches(spec, mapping, *, batch_size=None, num_batches=None): """Author batches on CPU avoid a GPU synchronization per junk position.""" from hebbian.transformer.data import AssociativeRecallBatchGenerator
return AssociativeRecallBatchGenerator( mapping, spec["num_facts"], spec["junk_vocab_size"], spec["junk_len"], spec["junk_len"], batch_size or spec["batch_size"], num_batches or spec["reader_steps"], device=torch.device("cpu"), )
def fixed_inputs(spec, mapping, seed): """Balanced keys and independently seeded junk, with the answer removed.""" with torch.random.fork_rng(devices=[]): torch.random.default_generator.manual_seed(seed) keys = torch.arange(spec["num_facts"]).repeat_interleave(spec["eval_repeats"]) inputs, _ = next(iter(make_batches(spec, mapping, batch_size=len(keys), num_batches=1))) inputs[:, spec["junk_len"]] = keys return inputs[:, :-1].contiguous(), keys
def _errors(actual, expected): relative = (actual - expected).norm(dim=-1) / expected.norm(dim=-1).clamp_min(1e-12) cosine = F.cosine_similarity(actual, expected, dim=-1).clamp(-1, 1) return relative, cosine.acos()
def _accuracy(scores, targets, changed): correct = scores.argmax(-1).eq(targets) return { "accuracy_all": correct.float().mean().item(), "accuracy_changed": correct[changed].float().mean().item() if changed.any() else None, "n_all": targets.numel(), "n_changed": int(changed.sum()), }
def _save_arrays(path, **arrays): np.savez_compressed( path, **{ name: value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else value for name, value in arrays.items() }, )
@torch.no_grad()def standalone(memory, factset, embeddings, changed, path): outputs = memory(factset.input_embeddings) targets = torch.tensor(factset.mapping.outputs, device=outputs.device) expected = factset.output_embeddings[targets] relative, angle = _errors(outputs, expected) normalized = F.normalize(outputs, dim=-1) fact_scores = normalized @ factset.output_embeddings.T full_scores = normalized @ embeddings.weight.T norm_error = (outputs.norm(dim=-1) - expected.norm(dim=-1)).abs() result = { "fact_accuracy": fact_scores.argmax(-1).eq(targets).float().mean().item(), "full_accuracy": full_scores.argmax(-1).eq(targets).float().mean().item(), "relative_error_mean": relative.mean().item(), "angle_radians_mean": angle.mean().item(), "norm_error_mean": norm_error.mean().item(), "output_norm_mean": outputs.norm(dim=-1).mean().item(), "full_vocab": _accuracy(full_scores, targets, changed.to(outputs.device)), "artifact": path.name, } _save_arrays( path, key=torch.arange(len(targets)), target=targets, changed_mapping=changed, pred=full_scores.argmax(-1), pred_fact=fact_scores.argmax(-1), scores=full_scores, scores_fact=fact_scores, scores_fact_raw=outputs @ factset.output_embeddings.T, relative_error=relative, angle_radians=angle, norm_error=norm_error, output_norm=outputs.norm(dim=-1), ) return result
@torch.no_grad()def evaluate_reader(model, inputs, keys, targets, changed, embeddings, batch_size, path=None): """Use actual query-position inputs to the MLP; never fit a predictor.""" device = next(model.parameters()).device cuda_devices = [device.index or 0] if device.type == "cuda" else [] scores, queries = [], [] was_training = model.training model.eval() hook = model.transformer.h[0].mlp.register_forward_pre_hook( lambda module, args: queries.append(args[0][:, -1].detach().cpu()) ) try: with torch.random.fork_rng(devices=cuda_devices): for batch in inputs.split(batch_size): logits, _ = model(batch.to(device)) scores.append(logits[:, 0].cpu()) finally: hook.remove() model.train(was_training) scores, queries = torch.cat(scores), torch.cat(queries) relative, angle = _errors(queries, embeddings.weight.detach().cpu()[keys]) result = _accuracy(scores, targets, changed) result.update( { "query_relative_error_mean": relative.mean().item(), "query_angle_radians_mean": angle.mean().item(), } ) if path is not None: _save_arrays( path, key=keys, target=targets, changed_mapping=changed, pred=scores.argmax(-1), scores=scores, query_input=queries, query_relative_error=relative, query_angle_radians=angle, ) result["artifact"] = path.name return result
def load_checkpoint(path, device="cpu"): """Load our tensor-only checkpoint; no refitting or custom-object unpickling.""" payload = torch.load(path, map_location="cpu", weights_only=True) spec = payload["spec"] _source(spec) if payload["kind"] == "memory": model = _new_memory(spec, device) else: from hebbian.transformer.model import GPT, GPTConfig
model = GPT(GPTConfig(**payload["gpt_config"])).to(device) model.transformer.h[0].mlp = _new_memory(spec, device) model.load_state_dict(payload["state_dict"], strict=True) names = set(payload.get("trainable_names", [])) for name, parameter in model.named_parameters(): parameter.requires_grad_(name in names) return model.eval(), payload
def run_world(spec, seed, output_dir, device): """Fit four memories and two A-readers; evaluate all fixed final crossings.""" spec = {**DEFAULT_SPEC, **spec} if ( min( spec[k] for k in ( "num_facts", "d_model", "hidden_dim", "mlp_epochs", "reader_steps", "eval_every", "eval_repeats", ) ) <= 0 ): raise ValueError("Dimensions and fixed training/evaluation budgets must be positive") if spec["mlp_cutoff"] >= 0: raise ValueError("This comparison requires the MLP loss cutoff to be disabled") _source(spec) from hebbian.transformer.fact_store import build_fact_mlp, build_factset, build_token_embeddings from hebbian.transformer.model import GPT from hebbian.transformer.train import _make_eval_factset from hebbian.transformer.utils import ( copy_embeddings_to_gpt, create_gpt_config, insert_mlp_into_gpt, )
output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) device = torch.device(device) torch.set_num_threads(spec["cpu_threads"]) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False if device.type == "cuda": torch.cuda.set_device(device) torch.cuda.reset_peak_memory_stats(device) started = time.perf_counter() config = make_config(spec, seed, device) factsets = {"A": build_factset(config, seed=seed)} factsets["B"] = _make_eval_factset(factsets["A"], seed=seed + 7777) embeddings = build_token_embeddings( factsets["A"], spec["junk_vocab_size"], embedding_init="spherical", dtype=torch.float32, seed=seed, ).to(device) mappings = {name: torch.tensor(fs.mapping.outputs) for name, fs in factsets.items()} changed = mappings["A"] != mappings["B"] inputs, keys = fixed_inputs(spec, factsets["A"].mapping, seed + 20000) _save_arrays( output_dir / "world.npz", inputs=inputs, key=keys, mapping_A=mappings["A"], mapping_B=mappings["B"], changed_mapping=changed, embeddings=embeddings.weight, ) summary = { "seed": seed, "spec": spec, "state": "running", "memories": {}, "readers": {}, "environment": { "python": platform.python_version(), "torch": torch.__version__, "numpy": np.__version__, "transformers": importlib.metadata.version("transformers"), "cuda": torch.version.cuda, "device": str(device), "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, }, "world": { "changed_facts": int(changed.sum()), "facts": spec["num_facts"], "test_inputs_hash": tensor_hash({"inputs": inputs}), "mapping_A": mappings["A"].tolist(), "mapping_B": mappings["B"].tolist(), }, }
def persist(): temporary = output_dir / "summary.tmp" temporary.write_text(json.dumps(summary, indent=2) + "\n") temporary.replace(output_dir / "summary.json")
memories = {} for loss in ("ce", "mse"): memories[loss], summary["memories"][loss] = {}, {} for name, factset in factsets.items(): stage = time.perf_counter() torch.manual_seed(seed) initial = _new_memory(spec, device) initial_hash = tensor_hash(initial.state_dict()) del initial memory, metrics = build_fact_mlp( config, factset, method_config=_memory_config(spec, loss, device) ) memory.eval().requires_grad_(False) memories[loss][name] = memory checkpoint = f"memory-{loss}-{name}.pt" torch.save( { "kind": "memory", "spec": spec, "seed": seed, "loss": loss, "mapping": name, "state_dict": {k: v.detach().cpu() for k, v in memory.state_dict().items()}, }, output_dir / checkpoint, ) _save_arrays( output_dir / f"memory-{loss}-{name}-curve.npz", train_loss=np.asarray(metrics["train_losses"]), ) assert len(metrics["train_losses"]) == spec["mlp_epochs"] summary["memories"][loss][name] = { "initial_hash": initial_hash, "final_hash": tensor_hash(memory.state_dict()), "seconds": time.perf_counter() - stage, "checkpoint": checkpoint, "training_final_loss": metrics["train_losses"][-1], "training_final_fact_accuracy": metrics["final_accuracy"], } print(f"world {seed}: memory {loss}/{name} complete", flush=True) persist()
models = {} for loss in ("ce", "mse"): stage = time.perf_counter() torch.manual_seed(seed) gpt_config = create_gpt_config(config.train_config, config.dataset_config) model = GPT(gpt_config).to(device=device, dtype=torch.float32).eval() copy_embeddings_to_gpt(model, embeddings) insert_mlp_into_gpt(model, memories[loss]["A"], embeddings) initial_hash = tensor_hash(_state(model, non_mlp=True)) frozen_before = tensor_hash(_state(model, frozen=True)) optimizer = model.configure_optimizers( weight_decay=spec["reader_weight_decay"], learning_rate=spec["reader_lr"], betas=(0.9, 0.999), device_type=device.type, ) curve, stream_hash, train_loss_sum = [], hashlib.sha256(), 0.0 torch.manual_seed(seed + 10000) for step, (batch, labels) in enumerate(make_batches(spec, factsets["A"].mapping), 1): batch, labels = batch[:, :-1].contiguous(), labels[:, :-1].contiguous() stream_hash.update(batch.numpy().tobytes()) stream_hash.update(labels[:, -1].numpy().tobytes()) model.train() logits, _ = model(batch.to(device)) objective = F.cross_entropy(logits[:, 0], labels[:, -1].to(device)) optimizer.zero_grad(set_to_none=True) objective.backward() optimizer.step() train_loss_sum += objective.item() if step % spec["eval_every"] == 0 or step == spec["reader_steps"]: evaluation = evaluate_reader( model, inputs, keys, mappings["A"][keys], changed[keys], embeddings, spec["batch_size"], ) curve.append( {"step": step, "mean_training_loss": train_loss_sum / step, "A": evaluation} ) print( f"world {seed}: reader {loss} step {step}, A={evaluation['accuracy_all']:.4f}", flush=True, ) model.eval() models[loss] = model frozen_after = tensor_hash(_state(model, frozen=True)) assert frozen_after == frozen_before checkpoint = f"reader-{loss}.pt" torch.save( { "kind": "reader", "spec": spec, "seed": seed, "loss": loss, "gpt_config": asdict(gpt_config), "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()}, "trainable_names": [k for k, v in model.named_parameters() if v.requires_grad], }, output_dir / checkpoint, ) summary["readers"][loss] = { "initial_non_mlp_hash": initial_hash, "final_non_mlp_hash": tensor_hash(_state(model, non_mlp=True)), "frozen_hash_before": frozen_before, "frozen_hash_after": frozen_after, "training_stream_hash": stream_hash.hexdigest(), "curve": curve, "seconds": time.perf_counter() - stage, "checkpoint": checkpoint, "endpoints": {}, } persist()
stage = time.perf_counter() for loss, model in models.items(): for name in ("A", "B"): summary["memories"][loss][name]["standalone"] = standalone( memories[loss][name], factsets[name], embeddings, changed, output_dir / f"standalone-{loss}-{name}.npz", ) conditions = { "A": (memories[loss]["A"], "A"), "wrong_A_on_B": (memories[loss]["A"], "B"), "B_ce": (memories["ce"]["B"], "B"), "B_mse": (memories["mse"]["B"], "B"), } for condition, (memory, target_map) in conditions.items(): insert_mlp_into_gpt(model.eval(), memory, embeddings) result = evaluate_reader( model, inputs, keys, mappings[target_map][keys], changed[keys], embeddings, spec["batch_size"], output_dir / f"reader-{loss}-{condition}.npz", ) summary["readers"][loss]["endpoints"][condition] = result insert_mlp_into_gpt(model.eval(), memories[loss]["A"], embeddings) assert ( tensor_hash(_state(model, non_mlp=True)) == summary["readers"][loss]["final_non_mlp_hash"] ) initial_hashes = { v["initial_hash"] for losses in summary["memories"].values() for v in losses.values() } summary["audits"] = { "paired_memory_initializations": len(initial_hashes) == 1, "paired_reader_initializations": len( {r["initial_non_mlp_hash"] for r in summary["readers"].values()} ) == 1, "paired_training_streams": len( {r["training_stream_hash"] for r in summary["readers"].values()} ) == 1, "frozen_parameters_unchanged": all( r["frozen_hash_before"] == r["frozen_hash_after"] for r in summary["readers"].values() ), "future_answer_removed": inputs.shape[1] == 2 * spec["junk_len"] + 2, "B_used_for_reader_optimization_or_selection": False, } assert all( v for k, v in summary["audits"].items() if k != "B_used_for_reader_optimization_or_selection" ) summary["cost"] = { "memory_epochs_per_mapping_objective": spec["mlp_epochs"], "memory_fact_exposures_per_mapping_objective": spec["mlp_epochs"] * spec["num_facts"], "reader_steps_per_objective": spec["reader_steps"], "reader_tokens_per_objective": spec["reader_steps"] * spec["batch_size"] * (2 * spec["junk_len"] + 2), "reader_supervised_positions_per_objective": spec["reader_steps"] * spec["batch_size"], "peak_gpu_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, } summary["timing_seconds"] = { "final_evaluation": time.perf_counter() - stage, "whole_world": time.perf_counter() - started, } summary["state"] = "complete" persist() return summary123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Prospective Hebbian study: numerical calibration and auditable common primitives."""
from __future__ import annotations
import hashlibimport importlib.utilimport jsonimport mathimport osfrom datetime import datetime, timezonefrom pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[2]DATA = ROOT / "data/hebbian-learning-v1"RESULTS = ROOT / "results/hebbian-learning-v1"ARTIFACTS = ROOT / "docs/development-artifacts/hebbian-learning-v1"CONFIG_PATH = ROOT / "configs/hebbian-learning-v1.json"
def now(): return datetime.now(timezone.utc).isoformat()
def sha256(path): h = hashlib.sha256() with Path(path).open("rb") as f: for block in iter(lambda: f.read(4 * 1024 * 1024), b""): h.update(block) return h.hexdigest()
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(path.name + f".{os.getpid()}.tmp") tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") tmp.replace(path)
def read_json(path): return json.loads(Path(path).read_text())
def config(): return read_json(CONFIG_PATH)
def first_crossing(values, threshold): indices = np.flatnonzero(values <= threshold) return int(indices[0]) if len(indices) else None
def mode_prediction(rho, lr, steps, initial): factors = np.array([1 - lr * (1 + rho), 1 - lr * (1 - rho)]) if not np.all((factors > 0) & (factors < 1)): raise ValueError("The declared monotone discrete regime is required") return factors[None, :, None] ** np.arange(steps + 1)[:, None, None] * initial
def calibration_trajectory(phi, steps, lr, output_dim, checkpoint_nodes): """Actual matrix SGD, compared against an independently computed recurrence.""" phi = np.asarray(phi, dtype=np.float64) rho = float(phi[:, 0] @ phi[:, 1]) targets = np.eye(output_dim, 2, dtype=np.float64) weight = np.zeros((output_dim, phi.shape[0]), dtype=np.float64) modes = np.empty((steps + 1, 2, output_dim), dtype=np.float64) checkpoints = {} for step in range(steps + 1): error = weight @ phi - targets modes[step, 0] = (error[:, 0] + error[:, 1]) / math.sqrt(2) modes[step, 1] = (error[:, 0] - error[:, 1]) / math.sqrt(2) if step in checkpoint_nodes: checkpoints[str(step)] = weight.copy() if step < steps: weight -= lr * (error @ phi.T) predicted = mode_prediction(rho, lr, steps, modes[0]) norms = np.linalg.norm(modes, axis=2) predicted_norms = np.linalg.norm(predicted, axis=2) vector_errors = np.linalg.norm(modes - predicted, axis=2) eligible = predicted_norms > norms[0] * 1e-6 max_relative = float(np.max(vector_errors[eligible] / predicted_norms[eligible])) small_absolute = float(np.max(vector_errors[~eligible])) if (~eligible).any() else 0.0 crossings = [] for i, name in enumerate(["common", "difference"]): for epsilon in [0.1, 0.01]: factor = 1 - lr * (1 + rho if i == 0 else 1 - rho) predicted_step = math.ceil(math.log(epsilon) / math.log(factor)) observed = first_crossing(norms[:, i], epsilon * norms[0, i]) crossings.append( { "mode": name, "epsilon": epsilon, "predicted_step": predicted_step, "observed_step": observed, "right_censored": observed is None, "pass": (observed is None and predicted_step > steps) or (observed is not None and abs(observed - predicted_step) <= 1), } ) summary = { "rho": rho, "max_relative_vector_error": max_relative, "small_error_max_absolute": small_absolute, "crossings": crossings, "pass": max_relative <= 1e-7 and all(x["pass"] for x in crossings), } return summary, norms, predicted_norms, checkpoints
def calibrate(): import torch
cfg = config()["A"] out = RESULTS / "A" out.mkdir(parents=True, exist_ok=True) source = DATA / "source/hebbian-mlps/src/hebbian/methods/hebbian/model.py" spec = importlib.util.spec_from_file_location("locked_hebbian_model", source) author = importlib.util.module_from_spec(spec) spec.loader.exec_module(author) summaries = [] for kind in ["exact", "bilinear"]: for seed in cfg["seeds"]: for rho in cfg["rho"]: width = cfg["exact_width"] if kind == "exact" else cfg["input_dim"] rng = np.random.default_rng(seed) rotation = np.linalg.qr(rng.normal(size=(width, width)))[0] inputs = rotation[:, :2] @ np.array([[1, rho], [0, np.sqrt(1 - rho**2)]]) if kind == "bilinear": gen = torch.Generator().manual_seed(seed) a0 = torch.randn( cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 ) a1 = torch.randn( cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 ) feature_map = author.BilinearFeatureMap(a0, a1, normalize=True) raw_phi = feature_map(torch.from_numpy(inputs.T)).numpy().T else: raw_phi = inputs phi = raw_phi / np.linalg.norm(raw_phi, axis=0) summary, norms, prediction, weights = calibration_trajectory( phi, cfg["steps"], cfg["lr"], cfg["output_dim"], cfg["checkpoints"] ) run_id = f"{kind}-s{seed}-rho{rho}" summary.update( run_id=run_id, kind=kind, seed=seed, input_rho=rho, raw_gram=(raw_phi.T @ raw_phi).tolist(), unit_gram=(phi.T @ phi).tolist(), ) np.savez_compressed( out / f"{run_id}.npz", norms=norms, prediction=prediction, phi=phi, **{f"weight_{k}": v for k, v in weights.items()}, ) summaries.append(summary) print(run_id, summary["max_relative_vector_error"], summary["pass"], flush=True) audit = { "completed_at": now(), "config_sha256": sha256(CONFIG_PATH), "implementation_sha256": sha256(__file__), "author_file_sha256": sha256(source), "runs": summaries, "pass": all(x["pass"] for x in summaries), } write_json(ARTIFACTS / "A/audit.json", audit) if not audit["pass"]: raise RuntimeError("Stage A failed numerical acceptance") return audit
def q_auc(values, nodes): values, nodes = np.asarray(values), np.asarray(nodes) integrate = np.trapezoid if hasattr(np, "trapezoid") else np.trapz return integrate(values, nodes, axis=0) / nodes[-1]
def effective_rank(features): z = features / np.maximum(np.linalg.norm(features, axis=1, keepdims=True), 1e-8) gram = z @ z.T return float(np.trace(gram) ** 2 / np.square(gram).sum())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting."""
from __future__ import annotations
import copyimport hashlibimport osimport time
import numpy as npimport torchimport torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
from .hebbian_data import TEMPLATE, score_answerfrom .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, write_json
def tensor_hash(tensor): return hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
def state_hashes(model): return {name: tensor_hash(p) for name, p in model.state_dict().items()}
def aggregate_hash(hashes): return hashlib.sha256( "\n".join(f"{k}:{v}" for k, v in sorted(hashes.items())).encode() ).hexdigest()
def set_determinism(seed=0): os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") torch.set_num_threads(4) torch.manual_seed(seed) np.random.seed(seed) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.backends.cudnn.benchmark = False torch.use_deterministic_algorithms(True)
class QwenExperiment: def __init__(self, device="cuda:3"): set_determinism() self.cfg = config() self.device = torch.device(device) source = DATA / "source/qwen3-0.6b-base" self.tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True) self.tokenizer.pad_token = self.tokenizer.eos_token self.model = ( AutoModelForCausalLM.from_pretrained( source, local_files_only=True, torch_dtype=torch.float32, attn_implementation=self.cfg["model"]["attention"], ) .to(self.device) .eval() ) self.model.requires_grad_(False) self.layer = self.model.model.layers[self.cfg["model"]["layer"]] self.mlp = self.layer.mlp assert self.mlp.down_proj.weight.shape == (1024, 3072) assert self.mlp.up_proj.weight.numel() + self.mlp.gate_proj.weight.numel() == 6291456 self.base_local = {n: p.detach().clone() for n, p in self.mlp.named_parameters()} self.reference = None
def restore_base(self): with torch.no_grad(): for n, p in self.mlp.named_parameters(): p.copy_(self.base_local[n])
def configure_trainable(self, phase): self.model.requires_grad_(False) names = ["down_proj.weight"] if phase == "adapt" else ["up_proj.weight", "gate_proj.weight"] for name, p in self.mlp.named_parameters(): p.requires_grad_(name in names) return [p for p in self.model.parameters() if p.requires_grad]
def make_reference(self): self.reference = copy.deepcopy(self.model).eval().requires_grad_(False)
def rows(self, records, views=(0,)): return [(r, v, r["encoded"][v]) for r in records for v in views]
def batch(self, encoded, prompt_only=False): sequences = [ x["input_ids"][: x["answer_start"]] if prompt_only else x["input_ids"] for x in encoded ] width = max(map(len, sequences)) ids = torch.full( (len(sequences), width), self.tokenizer.pad_token_id, dtype=torch.long, device=self.device, ) attention = torch.zeros_like(ids) answer = torch.zeros_like(ids, dtype=torch.bool) for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): ids[i, : len(seq)] = torch.tensor(seq, device=self.device) attention[i, : len(seq)] = 1 if not prompt_only: answer[i, : len(seq)] = torch.tensor(enc["loss_mask"], device=self.device).bool() return ids, attention, answer
def hidden(self, ids, attention, model=None): return ( (model or self.model) .model(input_ids=ids, attention_mask=attention, use_cache=False) .last_hidden_state )
def ce(self, encoded, model=None): ids, attention, mask = self.batch(encoded) hidden = self.hidden(ids, attention, model) b, t = torch.where(mask[:, 1:]) logits = (model or self.model).lm_head(hidden[b, t]) losses = F.cross_entropy(logits, ids[b, t + 1], reduction="none") sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) counts = torch.bincount(b, minlength=len(encoded)) return sums / counts
def kl(self, encoded): if self.reference is None: raise RuntimeError("An episode-specific parent reference is required") ids, attention, mask = self.batch(encoded) b, t = torch.where(mask[:, 1:]) with torch.no_grad(): ref_hidden = self.hidden(ids, attention, self.reference) ref_log = F.log_softmax(self.reference.lm_head(ref_hidden[b, t]), dim=-1) logits = self.model.lm_head(self.hidden(ids, attention)[b, t]) losses = F.kl_div( F.log_softmax(logits, dim=-1), ref_log, reduction="none", log_target=True ).sum(-1) sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) return sums / torch.bincount(b, minlength=len(encoded))
def features(self, encoded, detach=True): captured = {}
def capture(module, args): captured["phi"] = args[0]
def capture_input(module, args): captured["x"] = args[0]
handle = self.mlp.down_proj.register_forward_pre_hook(capture) input_handle = self.mlp.register_forward_pre_hook(capture_input) try: ids, attention, _ = self.batch(encoded, prompt_only=True) if detach: with torch.no_grad(): hidden = self.hidden(ids, attention) positions = attention.sum(1) - 1 self.last_prompt_logits = self.model.lm_head( hidden[torch.arange(len(encoded), device=self.device), positions] ).detach() x = captured["x"][torch.arange(len(encoded), device=self.device), positions] self.last_layer_inputs = x.detach() self.original_features = ( F.linear(x, self.base_local["up_proj.weight"]) * F.silu(F.linear(x, self.base_local["gate_proj.weight"])) ).detach() else: self.hidden(ids, attention) phi = captured["phi"][ torch.arange(len(encoded), device=self.device), attention.sum(1) - 1 ] return phi.detach() if detach else phi finally: handle.remove() input_handle.remove()
@torch.no_grad() def generate(self, prompts, max_new_tokens=24): # Left-padding generation; positions are computed from the attention mask. self.tokenizer.padding_side = "left" inputs = self.tokenizer( prompts, padding=True, return_tensors="pt", add_special_tokens=False ).to(self.device) prompt_width = inputs.input_ids.shape[1] tokenizer = self.tokenizer
class StopAtNewline(StoppingCriteria): def __call__(self, input_ids, scores, **kwargs): texts = tokenizer.batch_decode( input_ids[:, prompt_width:], skip_special_tokens=True ) return torch.tensor(["\n" in text for text in texts], device=input_ids.device)
output = self.model.generate( **inputs, do_sample=False, max_new_tokens=max_new_tokens, pad_token_id=self.tokenizer.pad_token_id, eos_token_id=self.tokenizer.eos_token_id, use_cache=True, logits_to_keep=1, stopping_criteria=StoppingCriteriaList([StopAtNewline()]), ) tail = output[:, inputs.input_ids.shape[1] :] predictions = self.tokenizer.batch_decode(tail, skip_special_tokens=True) # Padding after a newline stop is not evidence of the model emitting EOS. eos_emitted = [] for row in tail: emitted = False for length, token in enumerate(row, 1): if int(token) == self.tokenizer.eos_token_id: emitted = True break if "\n" in self.tokenizer.decode(row[:length], skip_special_tokens=True): break eos_emitted.append(emitted) return predictions, eos_emitted
@torch.no_grad() def evaluate(self, records, views=(0, 1, 2), batch_size=24): rows = self.rows(records, views) result = [] for start in range(0, len(rows), batch_size): chunk = rows[start : start + batch_size] encoded = [x[2] for x in chunk] losses = self.ce(encoded).tolist() predictions, eos = self.generate([TEMPLATE.format(r["views"][v]) for r, v, _ in chunk]) phi = self.features(encoded) for i, (r, v, enc) in enumerate(chunk): prediction = predictions[i] first_token = enc["input_ids"][enc["answer_start"]] logits = self.last_prompt_logits[i] competitor_logits = logits.clone() competitor_logits[first_token] = -torch.inf competitor = int(competitor_logits.argmax()) result.append( { "case_id": r["case_id"], "relation_id": r["relation_id"], "subject_group": r["subject_group"], "view_id": v, "answer_nll": losses[i], "prediction": prediction, "answer_em": score_answer(prediction, r.get("aliases", [r["answer"]])), "eos_emitted": eos[i], "feature_norm": float(phi[i].norm()), "first_answer_nll": float(-logits.log_softmax(-1)[first_token]), "first_answer_margin": float(logits[first_token] - logits[competitor]), "current_competitor_token": competitor, "answer_tokens": enc["answer_tokens"], "prompt_tokens": enc["prompt_tokens"], } ) return result
def gradient(self, encoded): loss = self.ce([encoded]).mean() grad = torch.autograd.grad(loss, self.mlp.down_proj.weight)[0] return grad.detach(), float(loss.detach())
def verify_hooks_and_gradients(self, encoded): self.configure_trainable("adapt") captured = {}
def capture_input(module, args): captured["x"] = args[0].detach()
def capture_down(module, args, output): captured["phi"] = args[0].detach() output.retain_grad() captured["output"] = output
handles = [ self.mlp.register_forward_pre_hook(capture_input), self.mlp.down_proj.register_forward_hook(capture_down), ] try: self.model.zero_grad(set_to_none=True) self.ce([encoded]).mean().backward() with torch.no_grad(): expected_phi = self.mlp.up_proj(captured["x"]) * F.silu( self.mlp.gate_proj(captured["x"]) ) phi_error = float((expected_phi - captured["phi"]).abs().max()) delta = captured["output"].grad.double().flatten(0, 1) phi = captured["phi"].double().flatten(0, 1) reconstructed = delta.T @ phi actual = self.mlp.down_proj.weight.grad.double() grad_error = float((reconstructed - actual).norm() / actual.norm()) nonanswer_positions = encoded["answer_start"] - 1 prompt_grad_norm = float(delta[:nonanswer_positions].norm()) assert phi_error == 0.0 assert grad_error < 1e-5 return { "phi_max_absolute_error": phi_error, "gradient_relative_error": grad_error, "earlier_prompt_delta_norm": prompt_grad_norm, "all_positions_used": True, "trainable_parameters": sum( p.numel() for p in self.model.parameters() if p.requires_grad ), "pass": True, } finally: for handle in handles: handle.remove() self.model.zero_grad(set_to_none=True)
def run_baseline(device, shard=0, shards=1): engine = QwenExperiment(device) candidates = read_json(DATA / "candidates.json")[shard::shards] out = DATA / f"baseline-shard-{shard}.jsonl" finished = {} if out.exists(): for line in out.read_text().splitlines(): row = __import__("json").loads(line) finished[row["case_id"]] = row candidates = [r for r in candidates if r["case_id"] not in finished] start_time = time.monotonic() for start in range(0, len(candidates), 8): chunk = candidates[start : start + 8] rows = engine.evaluate(chunk) with out.open("a") as f: for record in chunk: item = { "case_id": record["case_id"], "views": [r for r in rows if r["case_id"] == record["case_id"]], } f.write(__import__("json").dumps(item, ensure_ascii=False) + "\n") if start % 80 == 0: print( f"baseline shard={shard} {start + len(chunk)}/{len(candidates)} " f"elapsed={time.monotonic() - start_time:.1f}s", flush=True, ) write_json( ARTIFACTS / f"baseline-shard-{shard}-complete.json", {"time": now(), "rows": len(candidates) + len(finished), "shards": shards}, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Development-only predictor fitting and episode-cluster paired inference."""
from __future__ import annotations
import itertools
import numpy as np
from .hebbian_learning import ( ARTIFACTS, DATA, RESULTS, config, now, q_auc, read_json, sha256, write_json,)
def fit_ridge(x, y, alpha): mean, scale = x.mean(0), x.std(0) scale = np.where(scale > 1e-12, scale, 1) z = (x - mean) / scale intercept = float(y.mean()) coef = np.linalg.solve(z.T @ z + alpha * np.eye(z.shape[1]), z.T @ (y - intercept)) return { "mean": mean.tolist(), "scale": scale.tolist(), "coefficients": coef.tolist(), "intercept": intercept, "alpha": alpha, "n_features": x.shape[1], }
def predict(model, x): x = x[:, : model["n_features"]] return ((x - model["mean"]) / model["scale"]) @ np.array(model["coefficients"]) + model[ "intercept" ]
def fact_trajectories(path): evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] nodes = [e["rows"][0]["step"] for e in evaluations] by_node = [{(r["case_id"], r["view_id"]): r for r in e["rows"]} for e in evaluations] cases = sorted({r["case_id"] for r in evaluations[0]["rows"]}) result = [] for case in cases: rewrite = [np.mean([rows[case, v]["answer_em"] for v in [1, 2]]) for rows in by_node] standard = [rows[case, 0]["answer_em"] for rows in by_node] all_correct = [all(rows[case, v]["answer_em"] for v in range(3)) for rows in by_node] sustained = next( (i for i in range(len(nodes) - 1) if all_correct[i] and all_correct[i + 1]), None ) first = by_node[0][case, 0] result.append( { "case_id": case, "q_auc": float(q_auc(rewrite, nodes)), "q_gain_auc": float(q_auc(np.array(rewrite) - rewrite[0], nodes)), "standard_auc": float(q_auc(standard, nodes)), "nodes": nodes, "rewrite_accuracy": rewrite, "standard_accuracy": standard, "sustained_step": nodes[sustained] if sustained is not None else None, "sustained_exposures": by_node[sustained][case, 0]["exposures"] if sustained is not None else None, "endpoint_first_success": sustained is None and all_correct[-1], "right_censored": sustained is None, "relation_id": first["relation_id"], } ) return result
def freeze_b(): from .hebbian_train import frozen_training_sources, run_summary, select_config
episodes = read_json(DATA / "episodes.json")["B_dev"] candidates = [] for lr in config()["adapt"]["learning_rates"]: summaries = [run_summary(RESULTS / f"B/dev-lr{lr:g}-e{i}") for i in range(len(episodes))] candidates.append( { "learning_rate": lr, "q_auc": float(np.mean([s["q_auc"] for s in summaries])), "keep_damage": float(np.mean([s["keep_damage"] for s in summaries])), "episodes": summaries, } ) chosen = select_config(candidates, "q_auc", True) lr = chosen["learning_rate"] x, y, groups = [], [], [] for episode in range(len(episodes)): path = RESULTS / f"B/dev-lr{lr:g}-e{episode}" if not (path / "complete.json").exists(): raise RuntimeError("All B_dev runs must have completion receipts") outcomes = {r["case_id"]: r["q_auc"] for r in fact_trajectories(path)} for row in read_json(path / "prospective-features.json")["rows"]: x.append(row["features"]) y.append(outcomes[row["case_id"]]) groups.append(episode) x, y, groups = np.array(x), np.array(y), np.array(groups) predictors = {} for name, width in [("P0", 4), ("P1", 8), ("P2", 10)]: scores = {} for alpha in config()["statistics"]["ridge_grid"]: errors = [] for group in np.unique(groups): train = groups != group model = fit_ridge(x[train, :width], y[train], alpha) errors.append(np.mean(np.abs(predict(model, x[~train]) - y[~train]))) scores[alpha] = float(np.mean(errors)) best_alpha = min(scores, key=scores.get) predictors[name] = {**fit_ridge(x[:, :width], y, best_alpha), "cv_mae": scores} write_json( ARTIFACTS / "B-lock.json", { "time": now(), "status": "locked", "learning_rate": lr, "lr_candidates": candidates, "predictors": predictors, "source_hashes": frozen_training_sources(), "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), "fitting_scope": "B_dev only; fold-specific training standardization in episode CV", }, )
def paired_inference(differences): differences = np.asarray(differences, dtype=np.float64) rng = np.random.default_rng(config()["statistics"]["seed"]) n = len(differences) samples = differences[rng.integers(0, n, (10000, n))].mean(1) observed = float(differences.mean()) signs = np.array(list(itertools.product([-1, 1], repeat=n))) p = float(np.mean(np.abs((signs * differences).mean(1)) >= abs(observed) - 1e-14)) return { "mean": observed, "ci95": np.quantile(samples, [0.025, 0.975]).tolist(), "exact_two_sided_sign_p": p, "episode_differences": differences.tolist(), "n_episodes": n, }
def rankdata(values): values = np.asarray(values) order = np.argsort(values, kind="stable") ranked = np.empty(len(values), dtype=float) i = 0 while i < len(values): j = i + 1 while j < len(values) and values[order[j]] == values[order[i]]: j += 1 ranked[order[i:j]] = (i + j - 1) / 2 i = j return ranked
def spearman(x, y): a, b = rankdata(x), rankdata(y) return float(np.corrcoef(a, b)[0, 1]) if a.std() and b.std() else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811"""Paired formation/adaptation, prospective diagnostics and exact state resumption."""
from __future__ import annotations
import itertoolsimport jsonimport randomimport time
import numpy as npimport torchimport torch.nn.functional as F
from .hebbian_learning import ( ARTIFACTS, CONFIG_PATH, DATA, RESULTS, ROOT, config, effective_rank, now, q_auc, read_json, sha256, write_json,)from .hebbian_model import ( QwenExperiment, aggregate_hash, set_determinism, state_hashes,)
def grouping(records, seed): """Exact minimum-cost derangements; random seeded ties, real CE labels unchanged.""" n = len(records) rng = np.random.default_rng(seed) permutations = [ p for p in itertools.permutations(range(n)) if all(i != j for i, j in enumerate(p)) ]
def cost(p): return sum( 10 * (records[i]["target_id"] == records[j]["target_id"]) + (records[i]["relation_id"] != records[j]["relation_id"]) for i, j in enumerate(p) )
costs = np.array([cost(p) for p in permutations]) best = np.flatnonzero(costs == costs.min()) p1, p2 = [permutations[int(rng.choice(best))] for _ in range(2)] groups = [(3 * i, 3 * p1[i] + 1, 3 * p2[i] + 2) for i in range(n)] return groups
def contrastive_loss(features, target_ids, groups, tau=0.1): z = F.normalize(features, dim=-1, eps=1e-8) similarities = z @ z.T / tau positive = torch.zeros_like(similarities, dtype=torch.bool) for group in groups: for i in group: for j in group: if i != j: positive[i, j] = True negative = torch.tensor([[a != b for b in target_ids] for a in target_ids], device=z.device) negative &= ~positive negative.fill_diagonal_(False) assert torch.all(positive.sum(1) == 2) assert torch.all(negative.sum(1) >= 1) allowed = positive | negative log_denominator = similarities.masked_fill(~allowed, -torch.inf).logsumexp(1) loss = (log_denominator - (similarities * positive).sum(1) / positive.sum(1)).mean() return loss, {"positive_pairs": int(positive.sum()), "negative_pairs": int(negative.sum())}
def optimizer(parameters, lr): cfg = config()["optimizer"] return torch.optim.AdamW( parameters, lr=lr, betas=tuple(cfg["betas"]), eps=cfg["eps"], weight_decay=cfg["weight_decay"], )
def replay_batch(pools, texts, step): facts = pools["R_keep"] return [facts[(step * 6 + i) % len(facts)]["encoded"][0] for i in range(6)] + [ texts["train"][(step * 2 + i) % len(texts["train"])] for i in range(2) ]
def frozen_training_sources(): paths = [CONFIG_PATH] + sorted((ROOT / "src/llm_memory_editability").glob("hebbian*.py")) paths += [ROOT / "scripts/run_hebbian_learning.py"] return {str(p.relative_to(ROOT)): sha256(p) for p in paths}
def save_checkpoint(path, engine, opt, step, meta, ledger): state = { "parameters": {n: p.detach().cpu().clone() for n, p in engine.mlp.named_parameters()}, "optimizer": opt.state_dict(), "step": step, "data_cursor": step, "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(engine.device) if engine.device.type == "cuda" else None, "numpy_rng": np.random.get_state(), "python_rng": random.getstate(), "meta": meta, "ledger": ledger, } tmp = path.with_name(path.name + ".tmp") torch.save(state, tmp) tmp.replace(path)
def restore_checkpoint(path, engine, opt, meta): state = torch.load(path, map_location="cpu", weights_only=False) if state["meta"] != meta: raise RuntimeError(f"Checkpoint contract differs: {path}") with torch.no_grad(): for n, p in engine.mlp.named_parameters(): p.copy_(state["parameters"][n]) opt.load_state_dict(state["optimizer"]) torch.set_rng_state(state["torch_rng"]) if state["cuda_rng"] is not None: torch.cuda.set_rng_state(state["cuda_rng"], engine.device) np.random.set_state(state["numpy_rng"]) random.setstate(state["python_rng"]) return state["step"], state["ledger"]
def load_parent(engine, parent_path=None): engine.restore_base() if parent_path is not None: state = torch.load(parent_path, map_location="cpu", weights_only=False) with torch.no_grad(): for n, p in engine.mlp.named_parameters(): p.copy_(state["parameters"][n])
def gradient_cos(a, b): a, b = a.double(), b.double() return float((a * b).sum() / (a.norm() * b.norm()).clamp_min(1e-30))
def diagnose_episode(engine, records, replay, lr, out): """Saved before the learning trajectory; Adam candidate uses training data only.""" engine.configure_trainable("adapt") p = engine.mlp.down_proj.weight original = p.detach().clone() encoded = [r["encoded"][v] for r in records for v in range(3)] features = engine.features(encoded).double().cpu().numpy().reshape(len(records), 3, -1) unit = features / np.maximum(np.linalg.norm(features, axis=-1, keepdims=True), 1e-8) p0_gram = unit[:, 0] @ unit[:, 0].T rank = effective_rank(features[:, 0]) opt = optimizer([p], lr) opt.zero_grad(set_to_none=True) (engine.ce([r["encoded"][0] for r in records[:8]]).mean() + engine.kl(replay).mean()).backward() torch.nn.utils.clip_grad_norm_([p], 1.0) opt.step() delta = (p.detach() - original).clone() with torch.no_grad(): p.copy_(original) torch.save( {"delta_B": delta.cpu(), "phi": torch.from_numpy(features)}, out / "initial-diagnostics.pt" ) diagnostic = [] for i, record in enumerate(records): grads, losses = zip(*(engine.gradient(enc) for enc in record["encoded"]), strict=True) other = [ p0_gram[i, j] for j, r in enumerate(records) if r["target_id"] != record["target_id"] ] if not other: raise ValueError("Each episode needs different-answer facts") norms = np.linalg.norm(features[i], axis=1) feature_values = [ losses[0], record["encoded"][0]["answer_tokens"], record["encoded"][0]["prompt_tokens"], float(grads[0].double().norm()), float(np.mean(unit[i, 1:] @ unit[i, 0])), float(max(other)), float(norms[1:].mean() / norms[0]), rank, float(np.mean([gradient_cos(grads[0], g) for g in grads[1:]])), float(np.mean([float((g.double() * delta.double()).sum()) for g in grads[1:]])), ] diagnostic.append( { "case_id": record["case_id"], "features": feature_values, "p0_p1_cos": float(unit[i, 0] @ unit[i, 1]), "p0_p2_cos": float(unit[i, 0] @ unit[i, 2]), "feature_norms": norms.tolist(), "initial_nll": list(losses), } ) engine.model.zero_grad(set_to_none=True) assert torch.equal(p, original) write_json( out / "prospective-features.json", { "saved_at": now(), "rows": diagnostic, "information": { "P0": "initial answer NLL, lengths, labeled training gradient norm", "P1": "P0 plus prompt-only phi geometry", "P2": "P1 plus labeled evaluation gradients and training-only Adam candidate", }, }, ) return diagnostic
def first_order_calibration(engine, record, out): parameter = engine.mlp.down_proj.weight initial = parameter.detach().clone() source_grad, _ = engine.gradient(record["encoded"][0]) rows = [] for view in [1, 2]: encoded = record["encoded"][view] grad, nll0 = engine.gradient(encoded) ids, attention, _ = engine.batch([encoded], prompt_only=True) answer_token = encoded["input_ids"][encoded["answer_start"]] logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) competitor_logits = logits.detach().clone() competitor_logits[answer_token] = -torch.inf competitor = int(competitor_logits.argmax()) margin = logits[answer_token] - logits[competitor] margin_grad = torch.autograd.grad(margin, parameter)[0].detach() margin0 = float(margin.detach()) for relative_step in [1e-5, 1e-4]: proposal = ( -source_grad * (relative_step * initial.double().norm() / source_grad.double().norm()).float() ) with torch.no_grad(): parameter.copy_(initial + proposal) actual_delta = parameter - initial actual_nll = float(engine.ce([encoded])[0]) - nll0 new_logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) actual_margin = float(new_logits[answer_token] - new_logits[competitor]) - margin0 predicted_nll = float((grad.double() * actual_delta.double()).sum()) predicted_margin = float((margin_grad.double() * actual_delta.double()).sum()) parameter.copy_(initial) entry = { "case_id": record["case_id"], "view_id": view, "relative_step": relative_step, "competitor_token": competitor, "actual_nll_change": actual_nll, "predicted_nll_change": predicted_nll, "actual_margin_change": actual_margin, "predicted_margin_change": predicted_margin, } for name, actual, predicted in [ ("nll", actual_nll, predicted_nll), ("margin", actual_margin, predicted_margin), ]: entry[name + "_absolute_error"] = abs(actual - predicted) entry[name + "_relative_error"] = abs(actual - predicted) / max( abs(predicted), 1e-6 ) entry[name + "_sign_match"] = bool(np.sign(actual) == np.sign(predicted)) rows.append(entry) assert torch.equal(parameter, initial) write_json(out / "first-order-calibration.json", rows)
def geometry_rows(engine, records): encoded = [r["encoded"][v] for r in records for v in range(3)] features, originals = [], [] for start in range(0, len(encoded), 24): features.append(engine.features(encoded[start : start + 24]).double().cpu()) originals.append(engine.original_features.double().cpu()) phi = torch.cat(features).reshape(len(records), 3, -1) unit = F.normalize(phi, dim=-1) original = torch.cat(originals).reshape(len(records), 3, -1) original_cos = (unit * F.normalize(original, dim=-1)).sum(-1) gram = unit[:, 0] @ unit[:, 0].T rank = float(gram.trace().square() / gram.square().sum()) result = {} for i, r in enumerate(records): others = [ float(gram[i, j]) for j, other in enumerate(records) if other["target_id"] != r["target_id"] ] result[r["case_id"]] = { "same_fact_cos": float((unit[i, 1:] @ unit[i, 0]).mean()), "other_fact_cos": max(others) if others else None, "effective_rank": rank, "cosine_to_original_phi": float(original_cos[i].mean()), "dimension_variance": float(phi[:, 0].var(0, unbiased=False).mean()), } return result
def evaluate_node(engine, records, keep, texts, step, metadata, out, exposures, full_keep): rows = engine.evaluate(records) geometry = geometry_rows(engine, records) for row in rows: row.update( metadata, step=step, exposures=exposures.get(row["case_id"], 0), **geometry[row["case_id"]], ) payload = {"rows": rows} if full_keep: payload["keep"] = engine.evaluate(keep, views=(0,)) with torch.no_grad(): text_losses = [] for i in range(0, len(texts["test"]), 8): text_losses.extend(engine.ce(texts["test"][i : i + 8]).tolist()) payload["text_nll"] = float(np.mean(text_losses)) payload["text_ppl"] = float(np.exp(payload["text_nll"])) write_json(out / f"evaluation-{step:04d}.json", payload) return payload
def train_run( engine, phase, records, pools, texts, condition, seed, episode_id, split, lr, steps, run_id, lambda_geo=0.0, parent_path=None, diagnostics=False,): cfg = config() out = RESULTS / run_id out.mkdir(parents=True, exist_ok=True) load_parent(engine, parent_path) parent_hashes = state_hashes(engine.model) parent_hash = aggregate_hash(parent_hashes) parameters = engine.configure_trainable(phase) trainable = [n for n, p in engine.model.named_parameters() if p.requires_grad] meta = { "phase": phase, "split": split, "condition": condition, "seed": seed, "episode_id": episode_id, "parent_hash": parent_hash, "parent_path": str(parent_path) if parent_path else None, "source_hashes": frozen_training_sources(), "config_sha256": sha256(CONFIG_PATH), "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), "trainable_names": trainable, "lr": lr, "lambda_geo": lambda_geo, "steps": steps, "case_ids": [r["case_id"] for r in records], } if (out / "complete.json").exists(): receipt = read_json(out / "complete.json") if receipt["meta"] != meta: raise RuntimeError(f"Completed run contract changed: {run_id}") return receipt engine.make_reference() set_determinism(seed) random.seed(seed) opt = optimizer(parameters, lr) write_json(out / "contract.json", meta) ledger = { "answer_tokens": 0, "answer_input_tokens": 0, "replay_tokens": 0, "replay_input_tokens": 0, "geometry_input_tokens": 0, "forward_sequences": 0, "backward_sequences": 0, "optimizer_steps": 0, "wall_seconds": 0.0, } nodes = [n for n in cfg["form" if phase == "form" else "adapt"]["nodes"] if n <= steps] if steps not in nodes: nodes.append(steps) keep = pools["V_keep" if split == "dev" else "U_keep"] evaluate_records = pools["V_form"] if phase == "form" and split == "dev" else records rng = np.random.default_rng(seed) order = rng.permutation(len(records)).tolist() if phase == "form" else list(range(len(records))) exposures = {r["case_id"]: 0 for r in records} batch_table = [] for step in range(steps): batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] groups = ( grouping(batch, seed * 100000 + step) if condition == "C2" else [tuple(range(3 * i, 3 * i + 3)) for i in range(8)] ) batch_table.append({"case_ids": [r["case_id"] for r in batch], "groups": groups}) write_json(out / "batch-manifest.json", batch_table) checkpoints = sorted(out.glob("checkpoint-*.pt")) start = 0 if checkpoints: start, ledger = restore_checkpoint(checkpoints[-1], engine, opt, meta) for item in batch_table[:start]: for case_id in item["case_ids"]: exposures[case_id] += 1 elif diagnostics: diagnostic = diagnose_episode(engine, records, replay_batch(pools, texts, 0), lr, out) if split == "eval": from .hebbian_statistics import predict
predictors = read_json(ARTIFACTS / "B-lock.json")["predictors"] write_json( out / "prospective-predictions.json", { "saved_at": now(), "parent_hash": parent_hash, "predictions": [ { "case_id": r["case_id"], "values": { name: float(predict(model, np.array(r["features"])[None])[0]) for name, model in predictors.items() }, } for r in diagnostic ], }, ) first_order_calibration(engine, min(records, key=lambda r: r["case_id"]), out) metadata = { k: meta[k] for k in ["phase", "split", "condition", "seed", "episode_id", "parent_hash"] } if start == 0: save_checkpoint(out / "checkpoint-0000.pt", engine, opt, 0, meta, ledger) for step in range(start, steps + 1): if step in nodes: evaluate_node( engine, evaluate_records, keep, texts, step, metadata, out, exposures, full_keep=(phase == "form" or step in [0, 16, 64, 128]), ) if phase == "adapt" and condition.startswith("C") and step in [0, 16, 128]: gradients = [] for r in sorted(records, key=lambda r: r["case_id"])[:4]: grads = [engine.gradient(e)[0] for e in r["encoded"]] gradients.append( { "case_id": r["case_id"], "p0_p1_gradient_cos": gradient_cos(grads[0], grads[1]), "p0_p2_gradient_cos": gradient_cos(grads[0], grads[2]), } ) write_json(out / f"gradients-{step:04d}.json", gradients) if step in [0, 16, 64, 128, 256]: save_checkpoint(out / f"checkpoint-{step:04d}.pt", engine, opt, step, meta, ledger) if step == steps: break batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] encoded = [r["encoded"][v] for r in batch for v in (range(3) if phase == "form" else [0])] replay = replay_batch(pools, texts, step) torch.cuda.synchronize(engine.device) begin = time.monotonic() opt.zero_grad(set_to_none=True) ce = engine.ce(encoded).mean() ce.backward() kl = engine.kl(replay).mean() kl.backward() geo_value, pair_counts = 0.0, None if phase == "form": features = engine.features(encoded, detach=False) targets = [r["target_id"] for r in batch for _ in range(3)] geo, pair_counts = contrastive_loss(features, targets, batch_table[step]["groups"]) if lambda_geo: (lambda_geo * geo).backward() geo_value = float(geo.detach()) norm = torch.nn.utils.clip_grad_norm_(parameters, cfg["optimizer"]["clip"]) opt.step() torch.cuda.synchronize(engine.device) ledger["wall_seconds"] += time.monotonic() - begin ledger["answer_tokens"] += sum(sum(e["loss_mask"]) for e in encoded) ledger["answer_input_tokens"] += sum(len(e["input_ids"]) for e in encoded) ledger["replay_tokens"] += sum(sum(e["loss_mask"]) for e in replay) ledger["replay_input_tokens"] += sum(len(e["input_ids"]) for e in replay) if phase == "form": ledger["geometry_input_tokens"] += sum(e["answer_start"] for e in encoded) ledger["forward_sequences"] += ( len(encoded) + 2 * len(replay) + (len(encoded) if phase == "form" else 0) ) ledger["backward_sequences"] += ( len(encoded) + len(replay) + (len(encoded) if lambda_geo else 0) ) ledger["optimizer_steps"] += 1 for r in batch: exposures[r["case_id"]] += 1 with (out / "training.jsonl").open("a") as f: f.write( json.dumps( { "step": step + 1, "ce": float(ce.detach()), "kl": float(kl.detach()), "geo": geo_value, "gradient_norm": float(norm), "pairs": pair_counts, } ) + "\n" ) write_json( out / "status.json", {"step": step + 1, "steps": steps, "time": now(), "ledger": ledger} ) if (step + 1) % 16 == 0: print( run_id, step + 1, "ce", float(ce.detach()), "wall", ledger["wall_seconds"], flush=True, ) final_hashes = state_hashes(engine.model) unchanged = all( final_hashes[n] == digest for n, digest in parent_hashes.items() if n not in trainable ) assert unchanged, "A parameter outside the intervention scope changed" receipt = { "meta": meta, "completed_at": now(), "ledger": ledger, "unchanged_outside_scope": unchanged, "final_hashes": final_hashes, "final_model_hash": aggregate_hash(final_hashes), "exposures": exposures, "trainable_parameters": sum(p.numel() for p in parameters), "estimated_dense_full_backprop_flops_upper_bound": ( sum(p.numel() for p in engine.model.parameters()) * ( 6 * ledger["answer_input_tokens"] + 8 * ledger["replay_input_tokens"] + (6 if lambda_geo else 2) * ledger["geometry_input_tokens"] ) ), } write_json(out / "complete.json", receipt) return receipt
def run_summary(path): evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] nodes = [e["rows"][0]["step"] for e in evaluations] rewrite = [ np.mean([r["answer_em"] for r in e["rows"] if r["view_id"] in [1, 2]]) for e in evaluations ] keep0 = np.mean([r["answer_em"] for r in evaluations[0]["keep"]]) keep1 = np.mean([r["answer_em"] for r in evaluations[-1]["keep"]]) return { "q_auc": float(q_auc(rewrite, nodes)), "keep_damage": float(keep0 - keep1), "answer_nll": float(np.mean([r["answer_nll"] for r in evaluations[-1]["rows"]])), }
def select_config(candidates, metric, maximize): safe = [ r for r in candidates if r["keep_damage"] <= config()["statistics"]["keep_damage_reference"] ] if safe: return sorted(safe, key=lambda r: (-1 if maximize else 1) * r[metric])[0] return sorted( candidates, key=lambda r: (r["keep_damage"], (-1 if maximize else 1) * r[metric]) )[0]
def preflight(engine, pools, texts): records = pools["B_dev"][:8] audit = engine.verify_hooks_and_gradients(records[0]["encoded"][0]) before = state_hashes(engine.model) parameters = engine.configure_trainable("adapt") engine.make_reference() opt = optimizer(parameters, 1e-5) torch.cuda.reset_peak_memory_stats(engine.device) torch.cuda.synchronize(engine.device) start = time.monotonic() for step in range(3): opt.zero_grad(set_to_none=True) engine.ce([r["encoded"][0] for r in records]).mean().backward() engine.kl(replay_batch(pools, texts, step)).mean().backward() torch.nn.utils.clip_grad_norm_(parameters, 1.0) opt.step() torch.cuda.synchronize(engine.device) seconds = (time.monotonic() - start) / 3 engine.restore_base() assert before == state_hashes(engine.model) estimate = { "time": now(), "device": str(engine.device), "adapt_step_seconds": seconds, "peak_memory_bytes": torch.cuda.max_memory_allocated(engine.device), "formal_adapt_steps": 11264, "formal_adapt_gpu_hours": seconds * 11264 / 3600, "formation_estimate_factor": 3, "formal_formation_gpu_hours_estimate": seconds * 3 * 2304 / 3600, "excludes": [ "generation and NLL evaluation", "gradient diagnostics", "development", "disk IO", ], "microbatch_answer": 8, "microbatch_replay": 8, "reference_parent_restored": True, } write_json(ARTIFACTS / "estimate.json", estimate) write_json(ARTIFACTS / "qwen-interface-audit.json", audit) print(estimate, flush=True)
def dispatch(args): if not (ARTIFACTS / "data-lock.json").exists(): raise RuntimeError("data-lock is required before development or evaluation") data_lock = read_json(ARTIFACTS / "data-lock.json") for name, digest in data_lock["files"].items(): if sha256(DATA / name) != digest: raise RuntimeError(f"Frozen data changed: {name}") if not read_json(ARTIFACTS / "A/audit.json")["pass"]: raise RuntimeError("Stage A must pass before model training") pools = read_json(DATA / "pools.json") texts = read_json(DATA / "text.json") episodes = read_json(DATA / "episodes.json") by_id = {r["case_id"]: r for rows in pools.values() for r in rows} engine = QwenExperiment(args.device) if args.command == "preflight": return preflight(engine, pools, texts) if args.command == "diagnose": if args.split == "dev": learning_rates = config()["adapt"]["learning_rates"] else: learning_rates = [read_json(ARTIFACTS / "B-lock.json")["learning_rate"]] tasks = list(itertools.product(learning_rates, enumerate(episodes["B_" + args.split]))) for lr, (episode, ids) in tasks[args.shard :: args.shards]: run_id = f"B/{args.split}-lr{lr:g}-e{episode}" train_run( engine, "adapt", [by_id[i] for i in ids], pools, texts, "B", 0, episode, args.split, lr, 128, run_id, diagnostics=True, ) return b_lr = read_json(ARTIFACTS / "B-lock.json")["learning_rate"] if args.command == "form" and args.split == "dev": candidates = [] for lr in config()["form"]["learning_rates"]: run_id = f"C/dev-C0-lr{lr:g}" train_run( engine, "form", pools["F_form"], pools, texts, "C0", 10, -1, "dev", lr, 256, run_id ) candidates.append( {"learning_rate": lr, "run_id": run_id, **run_summary(RESULTS / run_id)} ) chosen = select_config(candidates, "answer_nll", False) lr = chosen["learning_rate"] formation_candidates = [{"condition": "C0", "lambda_geo": 0.0, **chosen}] for lam in config()["form"]["lambdas"]: run_id = f"C/dev-C1-lambda{lam:g}" train_run( engine, "form", pools["F_form"], pools, texts, "C1", 10, -1, "dev", lr, 256, run_id, lambda_geo=lam, ) formation_candidates.append( { "condition": "C1", "lambda_geo": lam, "run_id": run_id, **run_summary(RESULTS / run_id), } ) for item in formation_candidates: adapt_results = [] for episode, ids in enumerate(episodes["C_dev"]): run_id = f"C/adapt-dev-{item['condition']}-lambda{item['lambda_geo']:g}-e{episode}" train_run( engine, "adapt", [by_id[i] for i in ids], pools, texts, item["condition"], 10, episode, "dev", b_lr, 64, run_id, parent_path=RESULTS / item["run_id"] / "checkpoint-0256.pt", ) adapt_results.append(run_summary(RESULTS / run_id)) item["future_q_auc"] = float(np.mean([r["q_auc"] for r in adapt_results])) item["adapt_results"] = adapt_results best = select_config( [r for r in formation_candidates if r["condition"] == "C1"], "future_q_auc", True ) lam = best["lambda_geo"] train_run( engine, "form", pools["F_form"], pools, texts, "C2", 10, -1, "dev", lr, 256, "C/dev-C2-engineering", lambda_geo=lam, ) write_json( ARTIFACTS / "C-lock.json", { "time": now(), "learning_rate": lr, "lambda_geo": lam, "adapt_learning_rate": b_lr, "lr_candidates": candidates, "formation_candidates": formation_candidates, "source_hashes": frozen_training_sources(), "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), "seeds": [0, 1, 2], "conditions": ["C0", "C1", "C2"], "episodes": episodes["C_eval"], "status": "locked", }, ) return c_lock = read_json(ARTIFACTS / "C-lock.json") if args.command == "form": tasks = list(itertools.product(["C0", "C1", "C2"], [0, 1, 2])) for condition, seed in tasks[args.shard :: args.shards]: train_run( engine, "form", pools["F_form"], pools, texts, condition, seed, -1, "eval", c_lock["learning_rate"], 256, f"C/form-{condition}-s{seed}", lambda_geo=0.0 if condition == "C0" else c_lock["lambda_geo"], ) elif args.command == "adapt": tasks = list( itertools.product(["C0", "C1", "C2"], [0, 1, 2], enumerate(episodes["C_eval"])) ) for condition, seed, (episode, ids) in tasks[args.shard :: args.shards]: train_run( engine, "adapt", [by_id[i] for i in ids], pools, texts, condition, seed, episode, "eval", b_lr, 128, f"C/adapt-{condition}-s{seed}-e{episode}", parent_path=RESULTS / f"C/form-{condition}-s{seed}/checkpoint-0256.pt", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Replicate the existing state objective in two ordinary, independent GPT layers."""
from __future__ import annotations
import jsonfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from . import representation_alignment as originalfrom .grok_depth import write_jsonfrom .latent_scaling import build_world, model_digestfrom .storage_composition import data_digest, evaluate, file_hash
def validate_model(spec, model): if spec["layers"] != 2 or spec["repeats"] != 1: raise ValueError("This replication requires two independent layers, executed once") blocks = list(model.iter_blocks()) assert len(blocks) == 2 and blocks[0] is not blocks[1] assert not {p.data_ptr() for p in blocks[0].parameters()} & { p.data_ptr() for p in blocks[1].parameters() } assert all(p.requires_grad for p in model.parameters())
@torch.no_grad()def diagnose(model, world, device): """Original readout of a pure first-hop prefix; no fitted probe or final answer.""" model.eval() metrics, predictions = {}, {} for task in ("common_atomic", "familiar_test", "strict_test"): rows = world[task] prefixes = np.column_stack( (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1]) ) labels = rows[:, 2] guesses, cosines = [], [] for start in range(0, len(rows), 256): tokens = torch.as_tensor(prefixes[start : start + 256], device=device) targets = torch.as_tensor(labels[start : start + 256], device=device) _, state = model(tokens, return_bridge=True) logits = F.linear(model.ln_final(state), model.token.weight) guesses.append(logits.argmax(-1).cpu().numpy()) cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy()) guess, cosine = np.concatenate(guesses), np.concatenate(cosines) correct = guess == labels metrics[task] = dict( n=len(rows), first_hop_original_readout_accuracy=float(correct.mean()), mean_cosine_to_input_embedding=float(cosine.mean()), pure_prefix=True, ) predictions.update( {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine} ) return metrics, predictions
def train(spec, out, source, device): model = original.new_model(spec, "cpu") validate_model(spec, model) assert model_digest(model) == spec["initial_model_sha256"] assert data_digest(build_world(spec)) == spec["data_sha256"] del model # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact. original.train(spec, out, source, device) out = Path(out) payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) model = original.new_model(spec, device) model.load_state_dict(payload["model"]) metrics, predictions = diagnose(model, build_world(spec), device) write_json(out / "state-diagnostics.json", metrics) np.savez_compressed(out / "state-predictions.npz", **predictions)
def audit(out, device): """Independent process reload of full generation and original intermediate readout.""" out = Path(out) torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) spec = payload["spec"] model = original.new_model(spec, device) validate_model(spec, model) model.load_state_dict(payload["model"]) world = build_world(spec) stored_world = np.load(out / "world.npz") for key, value in world.items(): np.testing.assert_array_equal(value, stored_world[key]) assert data_digest(world) == spec["data_sha256"] complete = json.loads((out / "complete.json").read_text()) assert file_hash(out / "model.pt") == complete["model_sha256"] metrics, predictions = evaluate(model, world, "low", device) saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") maximum = 0.0 for key, value in predictions.items(): if key.endswith("nll"): maximum = max(maximum, float(np.max(np.abs(value - saved[key])))) np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(value, saved[key]) state_metrics, state_predictions = diagnose(model, world, device) saved_state = np.load(out / "state-predictions.npz") for key, value in state_predictions.items(): if key.endswith("cosine"): np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(value, saved_state[key]) write_json( out / "audit.json", dict( passed=True, metrics=metrics, state_metrics=state_metrics, max_nll_error=maximum, allow_tf32=True, independent_parameters=True, ), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759"""Local factual updates and downstream composition in existing aligned GPTs.
Cases are selected from the graph alone, before loading any model predictions.Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parentreplay reference. No composition labels or intermediate-state targets enteroptimization. Finite replay KL is a regularizer, not exact preservation."""
from __future__ import annotations
import copyimport hashlibimport jsonimport osimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import utc, write_jsonfrom .latent_scaling import build_world, model_digestfrom .representation_alignment import new_modelfrom .storage_composition import data_digest, file_hash, generate_rows, pack_sentences
ROLES = ("first", "second")STRATA = ("familiar", "strict")DEFAULT_NODES = (0, 32, 128, 512)
def _rows(values, width): return np.asarray(values, dtype=np.int64).reshape(-1, width)
def _unique(values, width): return _rows(sorted(set(map(tuple, _rows(values, width)))), width)
def _hash_json(value): return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
def _batch_hash(batch): digest = hashlib.sha256() for tensor in batch: array = tensor.detach().cpu().numpy() digest.update(str(array.dtype).encode()) digest.update(str(array.shape).encode()) digest.update(array.tobytes()) return digest.hexdigest()
def learned_atoms(world): """Only atomics actually supervised in the representation parent.""" return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3)
def composition_pools(world): """All legal untrained queries, plus the original holdout and training sets.""" trained = set(map(tuple, world["train_composite"])) full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) familiar = _rows([r for r in full if tuple(r) not in trained], 5) return { "familiar": familiar, "strict": world["strict_test"].copy(), "registered_familiar": world["familiar_test"].copy(), "train": world["train_composite"].copy(), }
def affected(rows, fact, role): """Whether a query uses this factual address, independently of its answer.""" columns = (0, 1) if role == "first" else (2, 3) return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1])
def rewrite(rows, old_fact, new_fact, role, lookup): result = rows.copy() mask = affected(rows, old_fact, role) if role == "first": result[mask, 2] = new_fact[2] for index in np.flatnonzero(mask): result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] else: result[mask, 4] = new_fact[2] return result
def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): """Return JSON-compatible selected cases and graph-only eligibility counts.
Each distinct atomic address receives at most one counterfactual per role. First-hop replacements stay in the original familiar/strict bridge group and change at least one affected untrained composition answer. Strict cases never borrow a bridge with composition experience from the familiar group. """ if per_cell < 1 or replay_n < 1: raise ValueError("Positive case and replay counts are required") world = build_world(parent_spec) atoms = learned_atoms(world) lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} pools = composition_pools(world) rng = np.random.default_rng(seed + int(parent_spec["world"])) candidates, qualification = [], {} for role in ROLES: for stratum in STRATA: rows = pools[stratum] addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) bridges = np.unique(rows[:, 2]) # Include all trained bridges in that group, even if the holdout # happens not to visit them (strict rows enumerate all chains). group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] group_bridges = np.unique(group[group[:, 1] >= 17, 0]) if stratum == "strict": familiar_bridges = world["background_atomic"] familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] group_bridges = np.setdiff1d(group_bridges, familiar_bridges) bridges = np.union1d(bridges, group_bridges) tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) eligible, replacement_count = [], 0 for old in addresses: impacted = rows[affected(rows, old, role)] choices = [] for value in bridges if role == "first" else tails: if value == old[2]: continue new = [int(old[0]), int(old[1]), int(value)] updated = rewrite(impacted, old, new, role, lookup) if np.any(updated[:, -1] != impacted[:, -1]): choices.append(new) replacement_count += len(choices) if choices: eligible.append((old.tolist(), choices)) key = f"{role}_{stratum}" qualification[key] = { "candidate_addresses": len(addresses), "eligible_addresses": len(eligible), "eligible_replacements": replacement_count, "untrained_queries": len(rows), } if len(eligible) < per_cell: raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") order = rng.permutation(len(eligible))[:per_cell] for serial, index in enumerate(order): old, choices = eligible[index] new = choices[int(rng.integers(len(choices)))] candidates.append( { "case_id": f"{key}-{serial:02d}", "role": role, "stratum": stratum, "old_fact": old, "new_fact": new, } ) for case in candidates: tasks, originals = case_tasks(world, case, replay_indices=None) necessary = set(map(tuple, tasks["necessary_atomic"])) allowed = [ i for i, row in enumerate(atoms) if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary ] if len(allowed) < replay_n: raise ValueError("Insufficient independent replay atomics") case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} return candidates, qualification
def case_tasks(world, case, replay_indices=None): """Construct E/R/U/D with address-based exclusions and recomputed truth.""" atoms = learned_atoms(world) lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} old, new, role = case["old_fact"], case["new_fact"], case["role"] if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: raise ValueError("An edit must replace one existing factual value") tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} originals, necessary = {}, [] for stratum, rows in composition_pools(world).items(): mask = affected(rows, old, role) tasks[f"U_{stratum}"] = rows[~mask].copy() old_rows = rows[mask].copy() new_rows = rewrite(old_rows, old, new, role, lookup) changed = old_rows[:, -1] != new_rows[:, -1] if stratum == "train": # Training-query transfer is reported separately from held-out D. name = f"T_{role}_train" originals[name] = old_rows tasks[name] = new_rows else: name = f"D_{role}_{stratum}" originals[name] = old_rows[changed] tasks[name] = new_rows[changed] same = f"S_same_answer_{role}_{stratum}" originals[same] = old_rows[~changed] tasks[same] = new_rows[~changed] if stratum in STRATA: for h, r1, b, r2, t in tasks[name]: prerequisite = (b, r2, t) if role == "first" else (h, r1, b) necessary.append(prerequisite) tasks["necessary_atomic"] = _unique(necessary, 3) replay = case.get("replay_indices", []) if replay_indices is None else replay_indices if len(set(replay)) != len(replay): raise ValueError("Replay indices must be unique") target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) if len(target) != 1 or int(target[0]) in replay: raise ValueError("Replay cannot contain the edited address") tasks["R_atomic"] = atoms[replay].copy() tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) return tasks, originals
def answer_batch(rows, device): """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" tokens, labels = pack_sentences(_rows(rows, 3)) positions = np.tile([4, 5, 6], (len(rows), 1)) targets = labels[np.arange(len(rows))[:, None], positions] expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) np.testing.assert_array_equal(targets, expected) return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets))
def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): target = model(target_batch[0], positions=target_batch[1]) ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) if parent_log.requires_grad: raise ValueError("Replay reference must be detached") kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() return ce + replay_weight * kl, ce, kl
def _generate(model, rows, device, batch_size): if len(rows): return generate_rows(model, rows, device, batch_size=batch_size) return ( {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, { "generated": np.empty((0, 3), dtype=np.int64), "correct": np.empty(0, dtype=bool), "answer_nll": np.empty(0), }, )
def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): """Full-pool scores and separately labelled prerequisite/parent subsets.""" metrics, raw = {}, {} for name, rows in tasks.items(): values, predictions = _generate(model, rows, device, batch_size) raw.update({f"{name}__{k}": v for k, v in predictions.items()}) if name in originals: old = originals[name] generated = predictions["generated"] changed = old[:, -1] != rows[:, -1] old_correct = (generated[:, 0] == old[:, -1]) & np.all( generated[:, 1:] == [5, 1], axis=1 ) prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] _m, needed = _generate(model, prerequisite, device, batch_size) edited_ok = metrics["E_new"]["accuracy"] == 1.0 covered = needed["correct"] & edited_ok baseline = parent_correct[name] valid_parent = baseline & changed correct = predictions["correct"] values.update( { "changed_answer_n": int(changed.sum()), "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, "parent_correct_n": int(baseline.sum()), "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, "new_following_parent_correct": float(correct[valid_parent].mean()) if valid_parent.any() else None, "old_retained_parent_correct": float(old_correct[valid_parent].mean()) if valid_parent.any() else None, "direct_edit_success": edited_ok, "necessary_atomic_correct_n": int(needed["correct"].sum()), "operation_correct_n": int(covered.sum()), "operation_correct_coverage": float(covered.mean()) if len(rows) else None, "new_following_operation_correct": float(correct[covered].mean()) if covered.any() else None, } ) raw[f"{name}__parent_correct"] = baseline raw[f"{name}__operation_correct"] = covered raw[f"{name}__old_correct"] = old_correct raw[f"{name}__necessary_generated"] = needed["generated"] raw[f"{name}__new_rows"] = rows raw[f"{name}__old_rows"] = old metrics[name] = values return metrics, raw
def editable_parameters(model, scope="mlp", block_index=0): prefix = f"blocks.{block_index}.mlp." selected = [ name for name, _ in model.named_parameters() if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") ] if scope not in {"mlp", "down"} or not selected: raise ValueError("Unknown or empty local parameter scope") for name, parameter in model.named_parameters(): parameter.requires_grad_(name in selected) parameter.grad = None return selected
def _configure(device): device = torch.device(device) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True if device.type == "cuda": torch.cuda.set_device(device) return device
def _load_parent(parent_dir, device): path = Path(parent_dir) / "model.pt" payload = torch.load(path, map_location="cpu", weights_only=False) model = new_model(payload["spec"], device).eval() model.load_state_dict(payload["model"]) world = build_world(payload["spec"]) if (Path(parent_dir) / "world.npz").exists(): with np.load(Path(parent_dir) / "world.npz") as saved: for name, rows in world.items(): np.testing.assert_array_equal(rows, saved[name]) return model, world, payload["spec"]
def _parent_masks(parent, originals, device, batch_size): return { name: _generate(parent, rows, device, batch_size)[1]["correct"] for name, rows in originals.items() }
def run(spec, out, device="cuda:0"): """Execute one parent, a graph-selected case set and optional development lr grid.
The caller owns source freezing, resource allocation and W&B startup. Each branch has run/learning/complete artifacts. Root ``step`` is a strictly increasing evaluation index, including every branch's unchanged node zero; ``optimizer_updates`` separately records cumulative optimization work. Target labels and replay KL positions have separate exposure counters. ``status.json`` retains completed-branch progress, explicitly labelled in the manifest; it does not define the tracking series' step axis. """ device = _configure(device) out = Path(out) out.mkdir(parents=True, exist_ok=True) if (out / "run.json").exists() or (out / "complete.json").exists(): raise FileExistsError(f"Do not overwrite an existing attempt: {out}") nodes = spec.get("nodes", list(DEFAULT_NODES)) if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: raise ValueError("Nodes must increase from zero to a positive fixed endpoint") rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): raise ValueError("Learning rates must be positive and unique") if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: raise ValueError("Learning-rate grids are development-only") arms = spec.get("arms", ["edit", "sham"]) if sorted(arms) != ["edit", "sham"]: raise ValueError("Every case requires paired edit and sham branches") parent, world, parent_spec = _load_parent(spec["parent_dir"], device) parent_hash = model_digest(parent) cases, qualification = graph_cases( parent_spec, seed=spec.get("candidate_seed", 780011), per_cell=spec.get("per_cell", 2), replay_n=spec.get("replay_n", 32), ) if "case_ids" in spec: requested = set(spec["case_ids"]) if not requested or not requested <= {c["case_id"] for c in cases}: raise ValueError("Unknown/empty fixed graph-selected case subset") cases = [c for c in cases if c["case_id"] in requested] manifest = { "spec": spec, "parent_spec": parent_spec, "cases": cases, "qualification": qualification, "case_sha256": _hash_json(cases), "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), "parent_model_sha256": parent_hash, "world_sha256": data_digest(world), "created_utc": utc(), "dtype": "float32", "allow_tf32": True, "pid": os.getpid(), "gpu": device.index if device.type == "cuda" else None, "branches": len(cases) * len(rates) * len(arms), "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), "learning_step_unit": "evaluation_index", "status_step_unit": "completed_branches", "scope_warning": "The selected MLP is shared across all repeated executions", } write_json(out / "run.json", manifest) write_json(out / "cases.json", cases) np.savez_compressed(out / "world.npz", **world) root_learning, branch_summaries, completed_steps = [], [], 0 started = time.perf_counter() training_seconds = 0.0 batch_size = spec.get("eval_batch_size", 512) for case in cases: tasks, originals = case_tasks(world, case) parent_correct = _parent_masks(parent, originals, device, batch_size) parent_metrics, parent_predictions = evaluate_case( parent, tasks, originals, parent_correct, case["role"], device, batch_size, ) case_out = out / case["case_id"] case_out.mkdir() np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) write_json(case_out / "parent-metrics.json", parent_metrics) np.savez_compressed(case_out / "tasks.npz", **tasks) replay_batch = answer_batch(tasks["R_atomic"], device) with torch.no_grad(): parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() for lr in rates: for arm in arms: branch_name = f"lr{lr:.8g}-{arm}" branch_out = case_out / branch_name branch_out.mkdir() model = copy.deepcopy(parent).eval() selected = editable_parameters( model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0), ) parameters = dict(model.named_parameters()) optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) target = tasks["E_new" if arm == "edit" else "E_old"] target_batch = answer_batch(target, device) write_json( branch_out / "run.json", { "case_id": case["case_id"], "arm": arm, "lr": lr, "parent_model_sha256": parent_hash, "editable_parameters": selected, "optimizer": "Adam, fresh state, zero weight decay", "sampling": "same fixed full replay batch on every update; no dropout", "old_fact_sha256": _hash_json(case["old_fact"]), "new_fact_sha256": _hash_json(case["new_fact"]), "target_batch_sha256": _batch_hash(target_batch), "replay_batch_sha256": _batch_hash(replay_batch), "parent_reference_sha256": _batch_hash((parent_log,)), "nodes": nodes, }, ) np.savez_compressed( branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() ) step, losses, history = 0, [], [] for node in nodes: if device.type == "cuda": torch.cuda.synchronize(device) began = time.perf_counter() while step < node: optimizer.zero_grad(set_to_none=True) loss, ce, kl = edit_objective( model, target_batch, replay_batch, parent_log, spec.get("replay_weight", 1.0), ) if not torch.isfinite(loss): raise FloatingPointError(f"Nonfinite edit loss at {step}") loss.backward() gradient_norm = torch.nn.utils.clip_grad_norm_( [parameters[n] for n in selected], spec.get("clip_norm", 1.0), ) optimizer.step() step += 1 losses.append( { "step": step, "loss": float(loss.detach()), "target_ce": float(ce.detach()), "replay_kl": float(kl.detach()), "gradient_norm": float(gradient_norm), } ) if device.type == "cuda": torch.cuda.synchronize(device) training_seconds += time.perf_counter() - began metrics, predictions = evaluate_case( model, tasks, originals, parent_correct, case["role"], device, batch_size, ) current_hash = model_digest(model) record = { "step": step, "metrics": metrics, "model_sha256": current_hash, "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] == 1, "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, "loss": losses[-1] if losses else None, } history.append(record) write_json(branch_out / "learning.json", history) write_json(branch_out / "losses.json", losses) np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) torch.save( { "edited_tensors": { n: parameters[n].detach().cpu().clone() for n in selected }, "model_sha256": current_hash, "step": step, }, branch_out / f"tensors-{step:06d}.pt", ) root_learning.append( { "step": len(root_learning), "branch_step": step, "completed_branches": len(branch_summaries) + int(step == nodes[-1]), "optimizer_updates": completed_steps + step, "case_id": case["case_id"], "arm": arm, "lr": lr, "metrics": metrics, "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), "target_supervised_tokens": (completed_steps + step) * 3, "replay_distillation_positions": (completed_steps + step) * len(tasks["R_atomic"]) * 3, } ) write_json(out / "learning.json", root_learning) write_json( out / "status.json", { "state": "running", "step": len(branch_summaries), "optimizer_updates": completed_steps + step, "budget": manifest["branches"], "case_id": case["case_id"], "arm": arm, "lr": lr, }, ) changed = [ n for n, t in model.state_dict().items() if not torch.equal(t, parent.state_dict()[n]) ] if set(changed) - set(selected) or model_digest(parent) != parent_hash: raise AssertionError("A frozen parameter or the parent changed") complete = { "case_id": case["case_id"], "role": case["role"], "stratum": case["stratum"], "lr": lr, "arm": arm, "path": str(branch_out.relative_to(out)), "metrics": metrics, "steps": step, "changed_tensors": changed, "parent_model_sha256": parent_hash, "final_model_sha256": current_hash, "delta_l2": float( torch.sqrt( sum( (parameters[n] - dict(parent.named_parameters())[n]).square().sum() for n in selected ) ).detach() ), "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), } write_json(branch_out / "complete.json", complete) branch_summaries.append(complete) completed_steps += step result = { "status": "complete", "branches": branch_summaries, "updates": completed_steps, "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "finished_utc": utc(), "case_sha256": manifest["case_sha256"], } write_json(out / "complete.json", result) write_json( out / "status.json", { "state": "complete", "step": len(branch_summaries), "optimizer_updates": completed_steps, "budget": manifest["branches"], }, ) return result
def audit(out, device="cuda:0"): """Reload every saved node from parent plus exact tensors and re-score it.""" device, out = _configure(device), Path(out) manifest = json.loads((out / "run.json").read_text()) spec = manifest["spec"] if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: raise AssertionError("Parent checkpoint hash changed") parent, world, parent_spec = _load_parent(spec["parent_dir"], device) if model_digest(parent) != manifest["parent_model_sha256"]: raise AssertionError("Parent model digest changed") cases, qualification = graph_cases( parent_spec, seed=spec.get("candidate_seed", 780011), per_cell=spec.get("per_cell", 2), replay_n=spec.get("replay_n", 32), ) if "case_ids" in spec: cases = [c for c in cases if c["case_id"] in spec["case_ids"]] if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: raise AssertionError("Graph-selected cases changed") if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: raise AssertionError("World qualification changed") summary = json.loads((out / "complete.json").read_text()) rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) expected_branches = { (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") } actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: raise AssertionError("The fixed paired branch matrix is incomplete") root_learning = json.loads((out / "learning.json").read_text()) nodes = spec.get("nodes", list(DEFAULT_NODES)) expected_evaluations = len(actual_branches) * len(nodes) if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( range(expected_evaluations) ): raise AssertionError("Root learning evaluation indices are incomplete or repeated") for index, row in enumerate(root_learning): branch_index, node_index = divmod(index, len(nodes)) updates = branch_index * nodes[-1] + nodes[node_index] if ( (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] or row["branch_step"] != nodes[node_index] or row["optimizer_updates"] != updates or row["target_supervised_tokens"] != updates * 3 or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 or "supervised_tokens" in row ): raise AssertionError("Root learning optimizer or exposure accounting changed") batch_size = spec.get("eval_batch_size", 512) checked_nodes, checked_predictions, max_error = 0, 0, 0.0 for case in cases: tasks, originals = case_tasks(world, case) parent_correct = _parent_masks(parent, originals, device, batch_size) for branch in summary["branches"]: if branch["case_id"] != case["case_id"]: continue directory = out / branch["path"] branch_spec = json.loads((directory / "run.json").read_text()) target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] target_batch = answer_batch(target, device) replay_batch = answer_batch(tasks["R_atomic"], device) with torch.no_grad(): reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) expected_hashes = { "old_fact_sha256": _hash_json(case["old_fact"]), "new_fact_sha256": _hash_json(case["new_fact"]), "target_batch_sha256": _batch_hash(target_batch), "replay_batch_sha256": _batch_hash(replay_batch), "parent_reference_sha256": _batch_hash((reference,)), } if any(branch_spec[key] != value for key, value in expected_hashes.items()): raise AssertionError("Target or paired replay provenance changed") history = json.loads((directory / "learning.json").read_text()) if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): raise AssertionError("Saved edit node matrix is incomplete") if ( file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") != branch["tensor_file_sha256"] ): raise AssertionError("Final exact tensor file hash changed") for record in history: state = torch.load( directory / f"tensors-{record['step']:06d}.pt", map_location="cpu", weights_only=True, ) model = copy.deepcopy(parent).eval() selected = editable_parameters( model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) ) if set(state["edited_tensors"]) != set(selected): raise AssertionError("Unexpected edited tensor scope") merged = model.state_dict() merged.update(state["edited_tensors"]) model.load_state_dict(merged) if model_digest(model) != record["model_sha256"]: raise AssertionError("Exact saved tensors did not reconstruct the model") metrics, predictions = evaluate_case( model, tasks, originals, parent_correct, case["role"], device, batch_size, ) with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: if set(saved.files) != set(predictions): raise AssertionError("Prediction keys changed") for name, actual in predictions.items(): if name.endswith("answer_nll"): np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) if len(actual): max_error = max( max_error, float(np.max(np.abs(actual - saved[name]))) ) else: np.testing.assert_array_equal(actual, saved[name]) checked_predictions += actual.size for name, values in metrics.items(): for key, value in values.items(): expected = record["metrics"][name][key] if key == "answer_nll" and value is not None: np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) elif value != expected: raise AssertionError(f"Re-scoring mismatch: {name}/{key}") checked_nodes += 1 result = { "passed": True, "nodes": checked_nodes, "array_elements": checked_predictions, "max_nll_error": max_error, "case_sha256": manifest["case_sha256"], "finished_utc": utc(), } write_json(out / "audit.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Use the existing W&B sidecar, finishing only after the independent audit."""
import argparseimport fcntlimport importlibimport jsonimport osimport timefrom pathlib import Path
from . import experiment_tracking as tracking
class ContainerSDK: def __init__(self, sdk, runtime): self.sdk, self.runtime = sdk, runtime
def __getattr__(self, name): return getattr(self.sdk, name)
def Settings(self, **options): options.pop("x_stats_pid", None) if self.runtime: options["x_stats_pid"] = self.runtime["host_pid"] options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) return self.sdk.Settings(**options)
class AuditedRunTracker(tracking.ArtifactRunTracker): def __init__(self, sdk, batch, path, settings): runtime_path = path / "container-runtime.json" runtime = tracking.read_json(runtime_path) super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) self.run.config.update( { key: self.metadata[key] for key in ( "parent_spec", "cases", "learning_step_unit", "status_step_unit", ) if key in self.metadata } ) if runtime: self.run.config.update({"container_runtime": runtime})
def poll(self): history = tracking.read_json(self.path / "learning.json") previous = None for record in history: step = int(record["step"]) if step > self.cursor: metrics = tracking.learning_metrics(record, previous) for key in ("case", "case_id", "condition", "variant", "arm"): if key in record: metrics["condition/" + key] = record[key] if "optimizer_updates" in record: metrics["evaluation/index"] = step metrics["condition/step_unit"] = "evaluation_index" metrics.pop("perf/updates_per_second", None) metrics.pop("perf/training_ms_per_update", None) if previous is not None: seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) if seconds > 0: metrics["perf/updates_per_second"] = updates / seconds self.run.log(metrics, step=step) self.cursor = step self.state["last_logged_step"] = step tracking.write_json(self.state_path, self.state) previous = record status_path = self.path / "status.json" if status_path.exists(): self.run.summary["training_state"] = tracking.read_json(status_path).get("state") failed = (self.path / "failure.json").exists() audit_path = self.path / "audit.json" audit = tracking.read_json(audit_path) if audit_path.exists() else {} audited = audit.get("passed") is True complete = (self.path / "complete.json").exists() and audited self.run.summary["has_failure_record"] = failed self.run.summary["independently_reloaded"] = audited if complete or failed: self.run.summary["scientific_final_step"] = self.cursor self.run.finish(exit_code=1 if failed else 0) # Preserve the authoritative resume cursor even when every point # was already on the server and this process logged no new points. self.state["last_logged_step"] = self.cursor tracking.write_json(self.state_path, self.state) return True return False
def discover_runs(runs_dir): return { path for path in Path(runs_dir).glob("*") if (path / "run.json").exists() and (path / "learning.json").exists() }
def final_step(path): history = tracking.read_json(path / "learning.json") return max((int(record["step"]) for record in history), default=-1)
def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): """Drain late-created runs and late final nodes before terminal exit.
SDK initialization and uploads may take longer than an entire scientific run. Consequently, a scan made before those calls is never an exit proof. Finished runs stay in this process's cursor map and are reopened only if their saved learning trajectory acquired an unlogged final node. """ root, runs_dir = Path(root), Path(runs_dir) tracker_factory = tracker_factory or AuditedRunTracker active, finished = {}, {} try: while True: for path in sorted(discover_runs(runs_dir)): if path in active or path in finished: continue active[path] = tracker_factory(sdk, root, path, settings) print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) for path, tracker in list(active.items()): current = tracking.read_json(path / "run.json") if current.get("pid") != tracker.metadata.get("pid"): tracker.close() tracker = tracker_factory(sdk, root, path, settings) active[path] = tracker if tracker.poll(): finished[path] = tracker.cursor del active[path] if once: return {str(path): cursor for path, cursor in finished.items()} manifest = root / "controller-state.json" state = tracking.read_json(manifest) if manifest.exists() else {} terminal = state.get("state") in { "complete", "finished_with_failures", "development_prerequisite_not_met", } # Rescan AFTER all SDK calls and after reading the controller's # terminal state, so runs born during initialization cannot vanish. fresh = discover_runs(runs_dir) stale = {path for path, cursor in finished.items() if final_step(path) > cursor} for path in stale: del finished[path] if terminal and not active: expected = {runs_dir / name for name in state.get("completed", [])} if missing := expected - fresh: raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") if fresh <= finished.keys(): result = { "passed": True, "registered_runs": len(finished), "runs": { path.name: { "last_logged_step": finished[path], "final_step": final_step(path), } for path in sorted(fresh) }, } tracking.write_json(root / "tracking-completion.json", result) return result if fresh - (active.keys() | finished.keys()): continue time.sleep(settings["poll_seconds"]) finally: for tracker in active.values(): tracker.close()
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, required=True) parser.add_argument("--runs-dir", type=Path) parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) parser.add_argument("--entity") parser.add_argument("--project") parser.add_argument("--mode", choices=("online", "offline")) parser.add_argument("--once", action="store_true") args = parser.parse_args() settings = tracking.read_json(args.defaults) for key in ("entity", "project", "mode"): settings[key] = ( getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] ) if not settings["enabled"]: raise SystemExit("Experiment tracking is disabled in the selected defaults") local = args.root / "tracking-wandb" local.mkdir(parents=True, exist_ok=True) sdk = importlib.import_module("wandb") with (local / "tracker.lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once)
if __name__ == "__main__": main()docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_transfer.pyAdded+653
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_readout_control.pyAdded+373
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_relation_response.pyAdded+187
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.pyAdded+372
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.pyAdded+192
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_control.pyAdded+242
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.pyAdded+446
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.pyAdded+446
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.pyAdded+327
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_train.pyAdded+353
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_reencoding.pyAdded+438
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bridge_workspace.pyAdded+1112
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_controls.pyAdded+64
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/capacity_scaling.pyAdded+193
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/cli.pyAdded+32
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/composition_curves.pyAdded+477
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/curve_tracking.pyAdded+36
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step.pyAdded+669
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.pyAdded+371
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/depth_step_mechanism.pyAdded+589
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiment_tracking.pyAdded+298
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/experiments.pyAdded+39
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth.pyAdded+431
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_bridge.pyAdded+631
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_data.pyAdded+281
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_depth_extension.pyAdded+73
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_data.pyAdded+346
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.pyAdded+549
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_model.pyAdded+108
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_loop_train.pyAdded+214
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop.pyAdded+278
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_data.pyAdded+397
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grok_usage_train.pyAdded+261
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_data.pyAdded+396
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_followup.pyAdded+103
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_future.pyAdded+148
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_interface.pyAdded+566
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_learning.pyAdded+187
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_model.pyAdded+339
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/hebbian_train.pyAdded+811
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/independent_alignment.pyAdded+124
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_editing.pyAdded+759
docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/interface_tracking.pyAdded+203