Archive experiment files (4/125)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/depth_step_mechanism.pyAdded+589
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/experiment_tracking.pyAdded+289
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/experiments.pyAdded+39
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth.pyAdded+431
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_bridge.pyAdded+631
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_data.pyAdded+281
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_extension.pyAdded+73
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_data.pyAdded+346
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_mechanism.pyAdded+549
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_model.pyAdded+108
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_train.pyAdded+214
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_multihop.pyAdded+278
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_usage_data.pyAdded+397
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_usage_train.pyAdded+261
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_data.pyAdded+396
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_followup.pyAdded+103
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_future.pyAdded+148
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_interface.pyAdded+566
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_learning.pyAdded+187
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_model.pyAdded+339
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_train.pyAdded+811
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/latent_scaling.pyAdded+311
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/latent_support.pyAdded+363
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/low_rank.pyAdded+138
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/memory_reuse.pyAdded+469
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/multihop_scaling.pyAdded+518
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/natural_composition_confirmation.pyAdded+687
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/natural_composition_confirmation_v2.pyAdded+687
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural.pyAdded+328
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural_data.pyAdded+147
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural_models.pyAdded+157
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_constraints.pyAdded+94
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_path_learning.pyAdded+416
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_path_train.pyAdded+627
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/recurrence_use.pyAdded+416
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/representation_alignment.pyAdded+269
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/small_lm_composition.pyAdded+543
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/small_lm_followup.pyAdded+558
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/storage_composition.pyAdded+424
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/storage_frontier.pyAdded+262
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/text_loss_source.pyAdded+256
- docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/text_pretrain.pyAdded+401
68 unmodified lines69707168 unmodified linesdata/realworld-loop-entity-v1/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -textdata/realworld-loop-entity-v1/tokenizer/tokenizer_config.json filter=lfs diff=lfs merge=lfs -textdata/realworld-loop-prefix-v1/prepared.json filter=lfs diff=lfs merge=lfs -text68 unmodified lines6970717268 unmodified linesdata/realworld-loop-entity-v1/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -textdata/realworld-loop-entity-v1/tokenizer/tokenizer_config.json filter=lfs diff=lfs merge=lfs -textdata/realworld-loop-prefix-v1/prepared.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/first-principles-review-20261004/data-synthesis/grokking-all-eight-curves.pdf filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589"""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"], }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""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 [ "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=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()): 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", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests.
Independent composition examples and optimization time are separate axes. Allblocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs.Historical experiments and their frozen implementations are left untouched."""
from __future__ import annotations
import hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_model import ModelConfigfrom .grok_depth import EpochStream, make_optimizer, utc, write_jsonfrom .grok_loop_model import LoopGPT, flopsfrom .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentencesfrom .storage_composition import build_world as historical_worldfrom .storage_frontier import SOURCE_FILES as STABILITY_SOURCESfrom .storage_frontier import learning_ratefrom .text_pretrain import WORDS
SOURCE_FILES = [ *STABILITY_SOURCES, "src/llm_memory_editability/latent_scaling.py", "scripts/run_latent_scaling.py", "tests/test_latent_scaling.py",]
def build_world(spec): world = historical_world(spec) pool = world["train_composite"] order = np.random.default_rng(spec["world"] + 880000).permutation(len(pool)) count = spec["composition_count"] count = len(pool) if count == "all" else count if isinstance(count, bool) or not isinstance(count, int) or not 0 < count <= len(pool): raise ValueError("Composition count must be a positive prefix of the fixed pool") world["available_composite"] = pool[order] world["train_composite"] = world["available_composite"][:count].copy() return world
def construct(spec, device): config = ModelConfig( vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=16, ) torch.manual_seed(spec["initialization"]) # R=1 is ordinary GPT. The wrapper permits the same trained single block to # be evaluated at other R, including the R=1 training baseline. return LoopGPT(config, spec["repeats"], spec["dropout"], "legacy_unique").to(device)
def model_digest(model): digest = hashlib.sha256() for key, value in sorted(model.state_dict().items()): digest.update(key.encode()) digest.update(value.detach().cpu().numpy().tobytes()) return digest.hexdigest()
def run_name(spec): return ( f"w{spec['world']}-i{spec['initialization']}-d{spec['width']}" f"-l{spec['layers']}-r{spec['repeats']}-n{spec['composition_count']}-s{spec['steps']}" )
def role_coverage(world): first = {(int(h), int(r)) for h, r, _b, _r2, _t in world["train_composite"]} second = {(int(b), int(r)) for _h, _r1, b, r, _t in world["train_composite"]} rows = world["familiar_test"] return { "first_atoms_used": len(first), "second_atoms_used": len(second), "familiar_both_composition_roles": float( np.mean( [ (int(h), int(r1)) in first and (int(b), int(r2)) in second for h, r1, b, r2, _t in rows ] ) ), }
def train(spec, out, source, device="cuda:0"): out = Path(out) out.mkdir(parents=True, exist_ok=True) if (out / "latest.pt").exists() or (out / "complete.json").exists(): raise FileExistsError(f"Do not overwrite a training attempt: {out}") if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: raise ValueError("Nodes must include initialization and the fixed endpoint") if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: raise ValueError("Nodes must increase and the batch must divide into three streams") 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.cuda.set_device(torch.device(device)) process_start = time.perf_counter() world = build_world(spec) np.savez_compressed(out / "world.npz", **world) digest = data_digest(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["common_atomic"], world["train_composite"], world["anchor_atomic"]] table = tuple( torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) ) sizes = [len(rows) for rows in strata] 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] batch = spec["batch_size"] graph = FullTokenStep(model, optimizer, table, batch) flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0
def measure(loss=None): metrics, predictions = evaluate(model, world, "low", 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, "composition_epochs": step * batch / 3 / sizes[1], } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) if step in spec["repeat_nodes"]: repeat_metrics[str(step)] = {} for repeat in spec["test_repeats"]: m, p = evaluate(model, world, "low", device, repeat) repeat_metrics[str(step)][str(repeat)] = m np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) write_json(out / "repeat-metrics.json", repeat_metrics) 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["common_atomic"]["accuracy"], "train": metrics["train_composite"]["accuracy"], "test": metrics["familiar_test"]["accuracy"], } ), flush=True, ) return row
measure() for end in spec["nodes"][1:]: torch.cuda.synchronize() started = time.perf_counter() while step < end: n = min(128, end - step) indices = [] for i, stream in enumerate(streams): drawn = stream.take(n * batch // 3).reshape(n, batch // 3) counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) indices.append(drawn + offsets[i]) indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) for j in range(n): lr.fill_(learning_rate(spec, step + j + 1)) loss = graph(indices[j]) step += n torch.cuda.synchronize() training_seconds += time.perf_counter() - started loss = float(loss) if not np.isfinite(loss): raise FloatingPointError(f"Nonfinite training loss at {step}") endpoint = measure(loss) np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) 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()), "independent_facts": sizes[0] + sizes[2], "composition_examples": sizes[1], "role_coverage": role_coverage(world), "endpoint": endpoint, "repeat_metrics": repeat_metrics, "training_seconds": training_seconds, "process_seconds": time.perf_counter() - process_start, "supervised_tokens": step * batch * 23 // 3, "padded_input_tokens": step * batch * 9, "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_predictions(actual, saved): maximum = 0.0 assert set(actual) == set(saved.files) for key, value in actual.items(): if key.endswith("answer_nll"): maximum = max(maximum, float(np.abs(value - saved[key]).max())) np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(value, saved[key]) return maximum
def compare_metrics(actual, saved): for task, values in actual.items(): for key, value in values.items(): if key == "answer_nll": np.testing.assert_allclose(value, saved[task][key], rtol=1e-5, atol=1e-5) else: assert value == saved[task][key]
def audit(out, device="cuda:0"): out = Path(out) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_device(torch.device(device)) result = json.loads((out / "complete.json").read_text()) assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) spec = saved["spec"] world = build_world(spec) assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] assert saved["step"] == spec["steps"] model = construct(spec, device) model.load_state_dict(saved["model"]) metrics, predictions = evaluate(model, world, "low", device) compare_metrics(metrics, result["endpoint"]["metrics"]) maximum = compare_predictions( predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") ) repeat_checks = 0 for node, repeats in result["repeat_metrics"].items(): checkpoint = torch.load( out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False ) model.load_state_dict(checkpoint["model"]) for repeat, expected in repeats.items(): actual, pred = evaluate(model, world, "low", device, int(repeat)) compare_metrics(actual, expected) maximum = max( maximum, compare_predictions( pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") ), ) repeat_checks += 1 exposures = np.load(out / "exposures.npz") for i in range(3): np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 assert np.ptp(exposures[f"stratum{i}"]) <= 1 checked = { "passed": True, "endpoint_tokens_exact": True, "repeat_checks": repeat_checks, "max_nll_difference": maximum, "nll_rtol": 1e-5, "nll_atol": 1e-5, "utc": utc(), } write_json(out / "audit.json", checked) return checked123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""Degree-matched support follow-up with isolated training and audit entry points.
The train/audit bodies are copied from latent_scaling.py at batch creation sohistorical sources retain their frozen hashes. Architecture, optimizer, sentencepacking, evaluation and streams are reused; only build_world selects support."""
from __future__ import annotations
import jsonimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport torch
from .grok_depth import EpochStream, make_optimizer, utc, write_jsonfrom .grok_loop_model import flopsfrom .latent_scaling import ( SOURCE_FILES as HISTORICAL_SOURCES,)from .latent_scaling import ( build_world as scaling_world,)from .latent_scaling import ( compare_metrics, compare_predictions, construct, model_digest, role_coverage,)from .latent_scaling import ( run_name as scaling_run_name,)from .storage_composition import ( FullTokenStep, audit_world, data_digest, evaluate, file_hash, pack_sentences,)from .storage_frontier import learning_rate
SOURCE_FILES = [*HISTORICAL_SOURCES, "src/llm_memory_editability/latent_support.py"]
def run_name(spec): return scaling_run_name(spec) + "-support-" + spec["support"]
def build_world(spec): """Select frozen legal edges; never use model scores or test pairs to choose.""" if spec.get("support") not in ("connected", "split"): raise ValueError("Unknown frozen support arm") indices = spec.get("composition_indices", []) if ( len(indices) != 512 or any(isinstance(i, bool) or not isinstance(i, int) for i in indices) or len(set(indices)) != 512 or indices != sorted(indices) or spec.get("composition_count") != 512 ): raise ValueError("Support must contain 512 unique sorted integer indices") world = scaling_world(dict(spec, composition_count="all")) pool = world["available_composite"] if indices[0] < 0 or indices[-1] >= len(pool): raise ValueError("Support index outside the fixed available pool") world["train_composite"] = pool[indices].copy() if len(set(map(tuple, world["train_composite"]))) != 512: raise ValueError("Support contains duplicate training chains") audit_world(world) expected = spec.get("frozen_data_sha256") if expected is not None and data_digest(world) != expected: raise RuntimeError("Rebuilt support data differ from the frozen digest") return world
def exposure_signature(world, counts=None): """Count actual sampled roles and column marginals, independently of streams.""" rows = world["train_composite"] if counts is None: counts = np.ones(len(rows), dtype=np.int64) if len(counts) != len(rows): raise ValueError("Exposure counter does not match the support") first, second = Counter(), Counter() columns = [Counter() for _ in range(5)] for row, count in zip(rows, counts, strict=True): h, r1, b, r2, _t = map(int, row) first[f"{h}:{r1}"] += int(count) second[f"{b}:{r2}"] += int(count) for col, value in enumerate(row): columns[col][str(int(value))] += int(count) return { "first_roles": dict(sorted(first.items())), "second_roles": dict(sorted(second.items())), "columns": [dict(sorted(c.items())) for c in columns], }
def support_components(world): """Independent adjacency traversal, including all available training roles.""" adjacency = {} for h, r1, b, r2, _t in world["available_composite"]: adjacency.setdefault(("l", int(h), int(r1)), set()) adjacency.setdefault(("r", int(b), int(r2)), set()) for h, r1, b, r2, _t in world["train_composite"]: left, right = ("l", int(h), int(r1)), ("r", int(b), int(r2)) adjacency[left].add(right) adjacency[right].add(left) seen, components = set(), 0 for root in adjacency: if root in seen: continue components += 1 stack = [root] seen.add(root) while stack: for neighbour in adjacency[stack.pop()]: if neighbour not in seen: seen.add(neighbour) stack.append(neighbour) return { "roles": len(adjacency), "components": components, "isolated_roles": sum(not neighbours for neighbours in adjacency.values()), }
def validate_nodes(spec): if spec["batch_size"] != 192 or any(node % 8 for node in spec["nodes"]): raise ValueError("Every measurement must complete the 512-chain epochs") if not set(spec["repeat_nodes"]) <= set(spec["checkpoint_nodes"]) <= set(spec["nodes"]): raise ValueError("Scans and checkpoints must use recorded learning nodes")
def train(spec, out, source, device="cuda:0"): validate_nodes(spec) if "frozen_data_sha256" not in spec: raise ValueError("Training requires a frozen data digest") if any(file_hash(path) != digest for path, digest in source.items()): raise RuntimeError("Training source differs from its frozen digest") out = Path(out) out.mkdir(parents=True, exist_ok=True) if (out / "latest.pt").exists() or (out / "complete.json").exists(): raise FileExistsError(f"Do not overwrite a training attempt: {out}") if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: raise ValueError("Nodes must include initialization and the fixed endpoint") if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: raise ValueError("Nodes must increase and the batch must divide into three streams") 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.cuda.set_device(torch.device(device)) process_start = time.perf_counter() world = build_world(spec) np.savez_compressed(out / "world.npz", **world) digest = data_digest(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["common_atomic"], world["train_composite"], world["anchor_atomic"]] table = tuple( torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) ) sizes = [len(rows) for rows in strata] 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] batch = spec["batch_size"] graph = FullTokenStep(model, optimizer, table, batch) flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0
def measure(loss=None): if step and not np.all(counts[1] == step * batch // 3 // 512): raise RuntimeError("Composition exposures must be exact complete epochs") metrics, predictions = evaluate(model, world, "low", 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, "composition_epochs": step * batch / 3 / sizes[1], } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) if step in spec["repeat_nodes"]: repeat_metrics[str(step)] = {} for repeat in spec["test_repeats"]: m, p = evaluate(model, world, "low", device, repeat) repeat_metrics[str(step)][str(repeat)] = m np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) write_json(out / "repeat-metrics.json", repeat_metrics) 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["common_atomic"]["accuracy"], "train": metrics["train_composite"]["accuracy"], "test": metrics["familiar_test"]["accuracy"], } ), flush=True, ) return row
measure() for end in spec["nodes"][1:]: torch.cuda.synchronize() started = time.perf_counter() while step < end: n = min(128, end - step) indices = [] for i, stream in enumerate(streams): drawn = stream.take(n * batch // 3).reshape(n, batch // 3) counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) indices.append(drawn + offsets[i]) indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) for j in range(n): lr.fill_(learning_rate(spec, step + j + 1)) loss = graph(indices[j]) step += n torch.cuda.synchronize() training_seconds += time.perf_counter() - started loss = float(loss) if not np.isfinite(loss): raise FloatingPointError(f"Nonfinite training loss at {step}") endpoint = measure(loss) np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) 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()), "independent_facts": sizes[0] + sizes[2], "composition_examples": sizes[1], "role_coverage": role_coverage(world), "support_components": support_components(world), "support_exposures": exposure_signature(world, counts[1]), "endpoint": endpoint, "repeat_metrics": repeat_metrics, "training_seconds": training_seconds, "process_seconds": time.perf_counter() - process_start, "supervised_tokens": step * batch * 23 // 3, "padded_input_tokens": step * batch * 9, "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 audit(out, device="cuda:0"): out = Path(out) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_device(torch.device(device)) result = json.loads((out / "complete.json").read_text()) assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) recorded = json.loads((out / "spec.json").read_text()) assert saved["spec"] == result["spec"] == recorded["spec"] assert saved["source"] == result["source"] == recorded["source"] assert all(file_hash(path) == digest for path, digest in result["source"].items()) spec = saved["spec"] validate_nodes(spec) assert "frozen_data_sha256" in spec world = build_world(spec) assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] assert data_digest(world) == recorded["data_sha256"] == spec["frozen_data_sha256"] with np.load(out / "world.npz") as archived: assert set(archived.files) == set(world) for key, rows in world.items(): np.testing.assert_array_equal(rows, archived[key]) assert saved["step"] == spec["steps"] model = construct(spec, device) assert model_digest(model) == result["initial_model_sha256"] model.load_state_dict(saved["model"]) metrics, predictions = evaluate(model, world, "low", device) compare_metrics(metrics, result["endpoint"]["metrics"]) maximum = compare_predictions( predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") ) repeat_checks = 0 for node, repeats in result["repeat_metrics"].items(): checkpoint = torch.load( out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False ) assert checkpoint["spec"] == spec and checkpoint["step"] == int(node) model.load_state_dict(checkpoint["model"]) for repeat, expected in repeats.items(): actual, pred = evaluate(model, world, "low", device, int(repeat)) compare_metrics(actual, expected) maximum = max( maximum, compare_predictions( pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") ), ) repeat_checks += 1 exposures = np.load(out / "exposures.npz") for i in range(3): np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 assert np.ptp(exposures[f"stratum{i}"]) <= 1 composition_counts = exposures["stratum1"] assert np.all(composition_counts == spec["steps"] * spec["batch_size"] // 3 // 512) assert exposure_signature(world, composition_counts) == result["support_exposures"] assert support_components(world) == result["support_components"] checked = { "frozen_data_exact": True, "archived_world_exact": True, "composition_complete_epochs": True, "role_exposures_exact": True, "passed": True, "endpoint_tokens_exact": True, "repeat_checks": repeat_checks, "max_nll_difference": maximum, "nll_rtol": 1e-5, "nll_atol": 1e-5, "utc": utc(), } write_json(out / "audit.json", checked) return checked123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Fully observed matrix representability; no training or editing algorithm.
The best approximation minimizes unweighted Frobenius error over *all* entries.It need not preserve unchanged facts exactly or prioritize requested edits.Numerical rank uses an absolute singular-value threshold, not an exact-rank proof."""
from numbers import Integral, Realfrom typing import Any
import numpy as np
def _matrix(value: Any, name: str = "matrix") -> np.ndarray: """Convert a nonempty, finite, real numeric matrix to float64.""" try: raw = np.asarray(value) except (TypeError, ValueError) as exc: raise ValueError(f"{name} must be a rectangular real numeric matrix") from exc if raw.ndim != 2 or 0 in raw.shape: raise ValueError(f"{name} must be a nonempty two-dimensional matrix") if raw.dtype.kind not in "iuf": raise ValueError(f"{name} must contain real numeric values") with np.errstate(over="ignore", invalid="ignore"): result = raw.astype(np.float64) if not np.isfinite(result).all(): raise ValueError(f"{name} must contain finite float64 values") return result
def _rank(value: Any, shape: tuple[int, int]) -> int: if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral): raise ValueError("rank must be a nonnegative integer") if not 0 <= value <= min(shape): raise ValueError(f"rank must be between 0 and {min(shape)}") return int(value)
def _tolerance(value: Any) -> float: if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): raise ValueError("atol must be a finite positive real number") value = float(value) if not np.isfinite(value) or value <= 0: raise ValueError("atol must be a finite positive real number") return value
def numerical_rank(matrix: Any, atol: float = 1e-10) -> int: """Count singular values strictly greater than the absolute tolerance.""" array = _matrix(matrix) tolerance = _tolerance(atol) return int(np.count_nonzero(np.linalg.svd(array, compute_uv=False) > tolerance))
def best_rank_approximation(matrix: Any, rank: int) -> np.ndarray: """Return a best rank-at-most-``rank`` Frobenius approximation using SVD.
``rank`` may be zero and may not exceed the smaller matrix dimension. The returned matrix is independent of the input. Tied singular values can make the optimum nonunique; NumPy's SVD selects one such optimum. """ array = _matrix(matrix) budget = _rank(rank, array.shape) left, values, right = np.linalg.svd(array, full_matrices=False) return (left[:, :budget] * values[:budget]) @ right[:budget, :]
def representation_gap(matrix: Any, rank: int, atol: float = 1e-10) -> int: """Return max(0, numerical target rank minus the available rank budget).""" array = _matrix(matrix) budget = _rank(rank, array.shape) return max(0, numerical_rank(array, atol=atol) - budget)
def evaluate_update(original: Any, target: Any, rank: int, atol: float = 1e-10) -> dict[str, Any]: """Report an update's analytical optimum under a fixed total rank budget.
``original`` and ``target`` must have identical shapes. The target is fitted directly, with no optimization path or restriction on the update rank. ``squared_error_lower_bound`` is the sum of discarded squared singular values (Eckart–Young–Mirsky); floating-point residuals may differ slightly.
Edited entries are exactly those where original and target differ. ``atol`` affects rank estimates only. RMSE is measured against the target separately on edited and retained entries; an empty group is represented by ``None``. The retained-entry metric measures collateral error at this global optimum, not the side effects of a learned editing algorithm. """ before = _matrix(original, "original") after = _matrix(target, "target") if before.shape != after.shape: raise ValueError("original and target must have identical shapes") budget = _rank(rank, after.shape) tolerance = _tolerance(atol) with np.errstate(over="ignore", invalid="ignore"): delta = _matrix(after - before, "target - original") left, values, right = np.linalg.svd(after, full_matrices=False) reconstruction = (left[:, :budget] * values[:budget]) @ right[:budget, :] residual = reconstruction - after edited = before != after target_rank = int(np.count_nonzero(values > tolerance)) gap = max(0, target_rank - budget) error = float(np.linalg.norm(residual, ord="fro")) lower_bound = float(np.sum(values[budget:] ** 2))
def group_rmse(mask: np.ndarray) -> float | None: return float(np.linalg.norm(residual[mask]) / np.sqrt(mask.sum())) if mask.any() else None
report = { "rank_budget": budget, "atol": tolerance, "original_rank": numerical_rank(before, tolerance), "target_rank": target_rank, "delta_rank": numerical_rank(delta, tolerance), "representation_gap": gap, "representable_within_rank_tolerance": gap == 0, "edit_count": int(edited.sum()), "original": before.tolist(), "target": after.tolist(), "delta": delta.tolist(), "reconstruction": reconstruction.tolist(), "singular_values": values.tolist(), "frobenius_error": error, "squared_frobenius_error": error**2, "squared_error_lower_bound": lower_bound, "edited_entry_rmse": group_rmse(edited), "retained_entry_rmse": group_rmse(~edited), } metrics = [ error, error**2, lower_bound, report["edited_entry_rmse"], report["retained_entry_rmse"], ] if not all(value is None or np.isfinite(value) for value in metrics): raise ValueError("matrix scale exceeds finite float64 error metrics; rescale the inputs") return report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469"""Learned two-hop retrieval followed by an independently fitted memory swap.
The pinned author implementation supplies the SwiGLU memory and GPT blocks.Only attention Q/K are learned by the reader. Replacement facts are never usedby its optimizer, and all evaluation uses continuous intermediate states."""
from __future__ import annotations
import hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from llm_memory_editability import hebbian_interface as interface
ARMS = ("ce", "aligned")
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
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, ensure_ascii=False, indent=2) + "\n") temporary.replace(path)
def cpu_state(model): return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
def hash_state(model, *, reader_only=False): return interface.tensor_hash( {k: v for k, v in model.state_dict().items() if not reader_only or ".mlp." not in k} )
def build_world(spec, seed): """Geometry, content and held-out heads use independent local random streams.""" n, d, j = spec["num_entities"], spec["d_model"], spec["junk_vocab_size"] rng = np.random.default_rng(seed) embeddings = rng.standard_normal((n + j + 1, d)).astype(np.float32) embeddings /= np.linalg.norm(embeddings, axis=-1, keepdims=True) mapping_a = np.arange(n + j + 1, dtype=np.int64) mapping_b = mapping_a.copy() mapping_a[:n] = rng.permutation(n) for _ in range(10000): candidate = rng.permutation(n) if np.all(candidate != mapping_a[:n]): mapping_b[:n] = candidate break else: raise RuntimeError("Failed to draw a changed independent permutation") order = np.random.default_rng(seed + 20000).permutation(n) n_train = int(n * spec["train_head_fraction"]) if not 0 < n_train <= n: raise ValueError("Composition-training head fraction must lie in (0, 1]") train_mask = np.zeros(n, dtype=bool) train_mask[order[:n_train]] = True return { "embeddings": embeddings, "mapping_A": mapping_a, "mapping_B": mapping_b, "train_mask": train_mask, "seed": np.asarray(seed), }
def data_audit(spec, world): n, j = spec["num_entities"], spec["junk_vocab_size"] for name in ("A", "B"): mapping = world[f"mapping_{name}"] assert np.array_equal(np.sort(mapping[:n]), np.arange(n)) assert np.array_equal(mapping[n:], np.arange(n, n + j + 1)) assert np.all(world["mapping_A"][:n] != world["mapping_B"][:n]) np.testing.assert_allclose(np.linalg.norm(world["embeddings"], axis=-1), 1, atol=2e-7) assert world["train_mask"].sum() == int(n * spec["train_head_fraction"]) a, b = world["mapping_A"], world["mapping_B"] return { "entities": n, "neutral_tokens": j + 1, "A_composition_training_heads": int(world["train_mask"].sum()), "A_composition_heldout_heads": int((~world["train_mask"]).sum()), "changed_atomic_facts": int((a[:n] != b[:n]).sum()), "changed_composite_answers": int((a[a[:n]] != b[b[:n]]).sum()), "passed": True, }
def make_inputs(spec, repeats, seed): """Each head occurs once per repeat; contexts contain only neutral tokens.""" n, j, length = spec["num_entities"], spec["junk_vocab_size"], spec["junk_length"] rng = np.random.default_rng(seed) keys = np.tile(np.arange(n, dtype=np.int64), repeats) inputs = rng.integers(n, n + j, (len(keys), length + 2), dtype=np.int64) positions = rng.integers(0, length + 1, len(keys)) inputs[np.arange(len(keys)), positions] = keys inputs[:, -1] = n + j return inputs, keys
def new_memory(spec, init, device): cfg = {**interface.DEFAULT_SPEC, **spec} interface._source(cfg) torch.manual_seed(init) return interface._new_memory(cfg, device)
class TwoHopReader(torch.nn.Module): """Two causal attention blocks with one shared, frozen fact MLP."""
def __init__(self, spec, embeddings, memory, init, device): super().__init__() interface._source(spec) from hebbian.transformer.model import GPT, GPTConfig
torch.manual_seed(init + 100000) cfg = GPTConfig( block_size=spec["junk_length"] + 2, vocab_size=len(embeddings), n_layer=2, n_head=1, n_embd=spec["d_model"], dropout=0.0, bias=False, mlp_residual=False, attn_residual=False, use_rope=False, no_positional_encoding=True, mlp_norm_type="unit_rmsnorm", attn_norm_type="rmsnorm", lm_head_norm_type="unit_rmsnorm", tie_embeddings=True, freeze_value_dense_identity=True, use_identity_mlp=True, ) self.gpt = GPT(cfg).to(device) with torch.no_grad(): self.gpt.transformer.wte.weight.copy_(torch.as_tensor(embeddings, device=device)) self.install(memory) self.gpt.requires_grad_(False) for block in self.gpt.transformer.h: block.attn.c_q.requires_grad_(True) block.attn.c_k.requires_grad_(True) self.scale = spec["readout_scale"]
def install(self, memory): memory.requires_grad_(False) for block in self.gpt.transformer.h: block.mlp = memory
def forward(self, inputs): x = self.gpt.transformer.wte(inputs) logits = [] for block in self.gpt.transformer.h: x = block(x) z = self.gpt.transformer.ln_f(x[:, -1]) logits.append(self.scale * self.gpt.lm_head(z)) return torch.stack(logits, dim=1)
def memory_objective(output, embeddings, labels, arm, alignment_weight): ce = F.cross_entropy(output @ embeddings.T, labels) alignment = (output - embeddings[labels]).square().sum(-1).mean() return ce + (alignment_weight if arm == "aligned" else 0.0) * alignment
@torch.no_grad()def clean_memory(memory, embeddings, mapping, n): output = memory(embeddings) cosine = F.normalize(output, dim=-1) @ embeddings.T pred = cosine.argmax(-1) return { "atomic_accuracy": float(pred[:n].eq(mapping[:n]).float().mean()), "neutral_accuracy": float(pred[n:].eq(mapping[n:]).float().mean()), "target_cosine": float(cosine[torch.arange(n, device=mapping.device), mapping[:n]].mean()), "output_norm": float(output[:n].norm(dim=-1).mean()), "vector_squared_error": float( (output[:n] - embeddings[mapping[:n]]).square().sum(-1).mean() ), }
def fit_memory(spec, world, mapping_name, arm, init, device, output_dir): """Only atomic labels appear here, including for the replacement memory.""" path = output_dir / f"memory-{mapping_name}.pt" if path.exists(): payload = torch.load(path, map_location="cpu", weights_only=True) model = new_memory(spec, init, device) model.load_state_dict(payload["state_dict"]) record = dict(payload["record"], reused_checkpoint=True) return model.requires_grad_(False).eval(), record memory = new_memory(spec, init, device) embeddings = torch.as_tensor(world["embeddings"], device=device) labels = torch.as_tensor(world[f"mapping_{mapping_name}"], device=device) optimizer = torch.optim.Adam(memory.parameters(), lr=spec["memory_lr"], foreach=False) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, spec["memory_steps"], eta_min=spec["memory_min_lr"] ) initial_hash = hash_state(memory) curve = [] began = time.perf_counter() for step in range(spec["memory_steps"] + 1): if step in spec["memory_nodes"]: metrics = clean_memory(memory, embeddings, labels, spec["num_entities"]) metrics.update(step=step, seconds=time.perf_counter() - began) curve.append(metrics) write_json(output_dir / f"memory-{mapping_name}-curve.json", curve) print(json.dumps(dict(stage=f"memory-{mapping_name}", arm=arm, **metrics)), flush=True) if step == spec["memory_steps"]: break memory.train() optimizer.zero_grad(set_to_none=True) loss = memory_objective( memory(embeddings), embeddings, labels, arm, spec["alignment_weight"] ) loss.backward() optimizer.step() scheduler.step() if device.type == "cuda": torch.cuda.synchronize(device) memory.eval().requires_grad_(False) record = dict( initial_hash=initial_hash, final_hash=hash_state(memory), steps=spec["memory_steps"], seconds=time.perf_counter() - began, metrics=clean_memory(memory, embeddings, labels, spec["num_entities"]), ) torch.save(dict(state_dict=cpu_state(memory), record=record), path) return memory, record
@torch.no_grad()def evaluate(reader, inputs, device, batch_size): reader.eval() return np.concatenate( [ reader(torch.as_tensor(inputs[start : start + batch_size], device=device)).cpu().numpy() for start in range(0, len(inputs), batch_size) ] )
def accuracy(pred, target, mask=None): correct = pred == target if mask is not None: correct = correct[mask] return float(correct.mean()) if len(correct) else None
def score_logits(logits, world, keys, mapping_name): """Full-pool scores and explicitly labelled prerequisite/changed subsets.""" pred = logits.argmax(-1) mapping = world[f"mapping_{mapping_name}"] y1, y2 = mapping[keys], mapping[mapping[keys]] train = world["train_mask"][keys] a, b = world["mapping_A"], world["mapping_B"] changed = a[a[keys]] != b[b[keys]] n = len(world["train_mask"]) # Inputs are arranged as complete n-head repeats; find each actual successor. successor_row = np.arange(len(keys)) // n * n + mapping[keys] assert np.array_equal(keys[successor_row], mapping[keys]) known = (pred[:, 0] == y1) & (pred[successor_row, 0] == mapping[mapping[keys]]) return { "n": len(keys), "one_hop": accuracy(pred[:, 0], y1), "two_hop": accuracy(pred[:, 1], y2), "two_hop_A_training_heads": accuracy(pred[:, 1], y2, train), "two_hop_A_heldout_heads": accuracy(pred[:, 1], y2, ~train), "two_hop_changed": accuracy(pred[:, 1], y2, changed), "changed_n": int(changed.sum()), "two_hop_both_atoms_correct": accuracy(pred[:, 1], y2, known), "both_atoms_correct_n": int(known.sum()), "both_atoms_correct_coverage": float(known.mean()), }
def reader_loss(logits, targets, train_mask): return ( F.cross_entropy(logits[:, 0], targets[:, 0]) + F.cross_entropy(logits[train_mask, 1], targets[train_mask, 1]) ) / 2
def fit_reader(spec, world, memory, init, device, output_dir): reader = TwoHopReader(spec, world["embeddings"], memory, init, device) path = output_dir / "reader-A.pt" if path.exists(): payload = torch.load(path, map_location="cpu", weights_only=True) reader.load_state_dict(payload["state_dict"]) return reader.eval(), payload["record"] initial_hash = hash_state(reader, reader_only=True) frozen_before = interface.tensor_hash( {k: p for k, p in reader.named_parameters() if not p.requires_grad} ) n = spec["num_entities"] seed = int(world["seed"]) train_inputs, _ = make_inputs(spec, spec["reader_steps"], seed + 30000) stream_hash = hashlib.sha256(train_inputs.tobytes()).hexdigest() train_inputs = torch.as_tensor( train_inputs.reshape(-1, n, spec["junk_length"] + 2), device=device ) mapping = torch.as_tensor(world["mapping_A"], device=device) targets = torch.stack((mapping[:n], mapping[mapping[:n]]), dim=1) train_mask = torch.as_tensor(world["train_mask"], device=device) eval_inputs, eval_keys = make_inputs(spec, spec["eval_repeats"], seed + 40000) parameters = [p for p in reader.parameters() if p.requires_grad] optimizer = torch.optim.AdamW( parameters, lr=spec["reader_lr"], weight_decay=spec["reader_weight_decay"], foreach=False ) curve = [] began = time.perf_counter() for step in range(spec["reader_steps"] + 1): if step in spec["reader_nodes"]: logits = evaluate(reader, eval_inputs, device, n) metrics = score_logits(logits, world, eval_keys, "A") curve.append(dict(step=step, seconds=time.perf_counter() - began, **metrics)) np.savez_compressed(output_dir / f"reader-node-{step:05d}.npz", logits=logits) torch.save(cpu_state(reader), output_dir / f"reader-node-{step:05d}.pt") write_json(output_dir / "reader-curve.json", curve) print(json.dumps(dict(stage="reader", step=step, **metrics)), flush=True) if step == spec["reader_steps"]: break reader.train() optimizer.zero_grad(set_to_none=True) loss = reader_loss(reader(train_inputs[step]), targets, train_mask) loss.backward() optimizer.step() if device.type == "cuda": torch.cuda.synchronize(device) frozen_after = interface.tensor_hash( {k: p for k, p in reader.named_parameters() if not p.requires_grad} ) assert frozen_before == frozen_after, "Frozen facts or embeddings changed" record = dict( initial_hash=initial_hash, final_hash=hash_state(reader, reader_only=True), frozen_hash=frozen_after, stream_hash=stream_hash, steps=spec["reader_steps"], seconds=time.perf_counter() - began, trainable_names=[k for k, p in reader.named_parameters() if p.requires_grad], trainable_parameters=sum(p.numel() for p in parameters), total_parameters=sum(p.numel() for p in reader.parameters()), metrics=curve[-1], ) torch.save(dict(state_dict=cpu_state(reader), record=record), path) return reader.eval(), record
def run(spec, world_seed, init, arm, output_dir, device): if arm not in ARMS: raise ValueError(arm) 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) world = build_world(spec, world_seed) np.savez_compressed(output_dir / "world.npz", **world) write_json(output_dir / "spec.json", spec) audit = data_audit(spec, world) started = time.perf_counter() result = dict( world=world_seed, init=init, arm=arm, spec=spec, data_audit=audit, status="running" ) write_json(output_dir / "status.json", result) memory_a, a_record = fit_memory(spec, world, "A", arm, init, device, output_dir) reader, reader_record = fit_reader(spec, world, memory_a, init, device, output_dir) # Replacement fitting happens only after the A reader has finished. memory_b, b_record = fit_memory(spec, world, "B", arm, init, device, output_dir) inputs, keys = make_inputs(spec, spec["eval_repeats"], world_seed + 40000) logits_a = evaluate(reader, inputs, device, spec["num_entities"]) non_memory_hash = hash_state(reader, reader_only=True) reader.requires_grad_(False) reader.install(memory_b) logits_b = evaluate(reader, inputs, device, spec["num_entities"]) assert hash_state(reader, reader_only=True) == non_memory_hash assert reader.gpt.transformer.h[0].mlp is reader.gpt.transformer.h[1].mlp assert hash_state(memory_b) == b_record["final_hash"] embeddings = torch.as_tensor(world["embeddings"], device=device) with torch.no_grad(): memory_arrays = { f"memory_{name}_output": mem(embeddings).cpu().numpy() for name, mem in (("A", memory_a), ("B", memory_b)) } np.savez_compressed( output_dir / "endpoints.npz", inputs=inputs, keys=keys, logits_A=logits_a, logits_B=logits_b, **memory_arrays, ) # Store a full swapped endpoint to permit a genuinely independent reload. torch.save(dict(state_dict=cpu_state(reader)), output_dir / "reader-B.pt") endpoints = { "A": score_logits(logits_a, world, keys, "A"), "B": score_logits(logits_b, world, keys, "B"), "wrong_A_on_B": score_logits(logits_a, world, keys, "B"), } length, d, h, vocab = ( spec["junk_length"] + 2, spec["d_model"], spec["hidden_dim"], len(embeddings), ) # Approximate multiply-add FLOPs. Backprop through frozen MLP still costs work. memory_flops = 2 * spec["memory_steps"] * (18 * vocab * d * h + 6 * vocab**2 * d) reader_flops = spec["reader_steps"] * ( 2 * ( 24 * spec["num_entities"] * length * d**2 + 12 * spec["num_entities"] * length**2 * d + 12 * spec["num_entities"] * length * d * h ) ) result.update( status="complete", memories=dict(A=a_record, B=b_record), reader=reader_record, endpoints=endpoints, assertions=dict( frozen_reader_after_swap=True, shared_memory=True, no_B_reader_training=True ), seconds=time.perf_counter() - started, budget=dict( memory_updates=sum( spec["memory_steps"] for r in (a_record, b_record) if not r.get("reused_checkpoint", False) ), reused_memory_updates=sum( spec["memory_steps"] for r in (a_record, b_record) if r.get("reused_checkpoint", False) ), reader_updates=spec["reader_steps"], atomic_exposures=sum( spec["memory_steps"] * spec["num_entities"] for r in (a_record, b_record) if not r.get("reused_checkpoint", False) ), reader_input_tokens=spec["reader_steps"] * spec["num_entities"] * length, reader_supervised_answers=spec["reader_steps"] * (spec["num_entities"] + int(world["train_mask"].sum())), approximate_matmul_flops=reader_flops + memory_flops * sum(not r.get("reused_checkpoint", False) for r in (a_record, b_record)) / 2, peak_gpu_bytes=torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, ), ) write_json(output_dir / "summary.json", result) write_json(output_dir / "status.json", dict(status="complete", seconds=result["seconds"])) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518"""Width, composition experience and compute depth in complete causal GPT models.
The data, full-token objective and generation scoring extend ``depth_step``.Support arms use nested training paths and identical held-out evaluation pools;four independent streams keep atomics and each hop length at 32 draws per step."""
from __future__ import annotations
import copyimport hashlibimport jsonimport timefrom functools import lru_cachefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from . import depth_stepfrom .depth_step import ( # noqa: F401 -- public interface reused by checkpoint analysis BOS, DATA_DEFAULTS, ENTITY_OFFSET, EOS, EVALUATION_SPLITS, HOPS, PAD, TRAIN_SPLITS, compare_metrics, compare_predictions, construct, data_digest, evaluate, generate_rows, pack_rows, prompt_rows, truth_path_details,)from .grok_depth import EpochStream, make_optimizer, utc, write_jsonfrom .grok_loop_model import flopsfrom .latent_scaling import model_digestfrom .storage_composition import FullTokenStep, file_hashfrom .storage_frontier import learning_rate
SUPPORT_LEVELS = (1.0, 4.0)ARCHITECTURES = ((2, 1), (4, 1), (1, 2), (1, 4))COMMON_SPLITS = ("atomic",) + tuple( f"{split}_{hop}" for hop in HOPS for split in ("familiar", "strict"))SOURCE_FILES = [ *depth_step.SOURCE_FILES, "src/llm_memory_editability/multihop_scaling.py", "scripts/run_multihop_scaling.py", "scripts/execute_multihop_scaling.py", "tests/test_multihop_scaling.py",]
@lru_cache(maxsize=16)def _reference_world(seed, settings): return depth_step.build_world({"world_seed": seed, **dict(settings), "phi": 4.0})
def _reference(spec): seed = spec.get("world_seed", spec.get("world")) if seed is None: raise ValueError("A fixed world_seed is required") settings = tuple( (key, spec.get(key, value)) for key, value in DATA_DEFAULTS.items() if key != "phi" ) return _reference_world(int(seed), settings)
def common_evaluation_digest(world): digest = hashlib.sha256() for name in COMMON_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()) digest.update(json.dumps(world["metadata"]["id_mask"]).encode()) return digest.hexdigest()
def build_world(spec): phi = float(spec.get("phi", 4.0)) if phi not in SUPPORT_LEVELS: raise ValueError("Support phi must be 1 or 4") reference = _reference(spec) world = {name: reference[name].copy() for name in EVALUATION_SPLITS} metadata = copy.deepcopy(reference["metadata"]) metadata.pop("dataset_sha256", None) metadata.pop("independent_audit", None) ids = sum(metadata["id_mask"]) selections = {} for hop in HOPS: name = f"train_{hop}" count = min(round(phi * ids), len(reference[name])) world[name] = reference[name][:count].copy() selections[str(hop)] = { "requested": round(phi * ids), "actual": count, "effective_phi": count / ids if ids else None, "high_support_count": len(reference[name]), "capped": round(phi * ids) > len(reference[name]), "prefix_indices": list(range(count)), } # Preserve source lineage without duplicating descriptive source statistics. metadata["source_worlds"] = { hop: { key: values[key] for key in ( "seed", "hops", "dataset_sha256", "counts", "phi_requested", "phi_actual", "train_composite_capped", "id_paths_total", "all_paths_total", "source_url", "source_commit", "source_file", "source_license", ) } for hop, values in metadata["source_worlds"].items() } metadata.update( phi=phi, reference_phi=4.0, reference_dataset_sha256=reference["metadata"]["dataset_sha256"], composition_support=selections, support_selection="Prefix of each phi=4 training array; no resampling of facts or tests", exposure_contract="32 atomic + 32 each of 2/3/4-hop examples per step", training_objective="All nonpadding next tokens including EOS; no intermediate targets", ) world["metadata"] = metadata metadata["common_evaluation_sha256"] = common_evaluation_digest(world) checked = audit_world(world) metadata["dataset_sha256"] = checked["dataset_sha256"] metadata["independent_audit"] = checked expected = spec.get("frozen_data_sha256") if expected is not None and expected != checked["dataset_sha256"]: raise ValueError("Rebuilt data differ from the frozen specification") expected_common = spec.get("common_evaluation_sha256") if expected_common is not None and expected_common != metadata["common_evaluation_sha256"]: raise ValueError("Common evaluation pools differ from the frozen specification") return world
def audit_world(world): checked = depth_step.audit_world(world) metadata = world["metadata"] phi = metadata["phi"] if phi not in SUPPORT_LEVELS or metadata.get("reference_phi") != 4.0: raise ValueError("Invalid nested support contract") reference = _reference(metadata) ids = sum(metadata["id_mask"]) for name in EVALUATION_SPLITS: expected = reference[name] if name.startswith("train_"): expected = expected[: min(round(phi * ids), len(expected))] if not np.array_equal(world[name], expected): raise ValueError("Common pools/nested support differ from reference: " + name) common = common_evaluation_digest(world) if common != metadata["common_evaluation_sha256"]: raise ValueError("Common evaluation digest differs") if reference["metadata"]["dataset_sha256"] != metadata["reference_dataset_sha256"]: raise ValueError("High-support reference differs") return { **checked, "low_support_is_high_support_prefix": True, "same_atomic_id_ood_and_heldout_pools_across_support": True, "common_evaluation_sha256": common, }
def run_name(spec): seed = spec.get("world_seed", spec.get("world")) return ( f"w{seed}-i{spec['initialization']}-d{spec['width']}-phi{spec['phi']:g}" f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" )
def _validate_spec(spec): depth_step._validate_spec(spec) if float(spec["phi"]) not in SUPPORT_LEVELS: raise ValueError("Unsupported composition support") if (spec["layers"], spec["repeats"]) not in ARCHITECTURES: raise ValueError("Unsupported architecture")
def _check_source(source): depth_step._check_source(source) required = {"src/llm_memory_editability/multihop_scaling.py", *depth_step.SOURCE_FILES} if not required <= set(source): raise RuntimeError("Source lock omits experiment dependencies")
def _validate_output(out): depth_step._validate_output(out)
def _device_setup(device): device = torch.device(device) torch.set_num_threads(1) # Standalone workers call this once; CPU integration checks may call twice. try: torch.set_num_interop_threads(1) except RuntimeError: pass if device.type == "cuda": torch.cuda.set_device(device) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True return device
class _CpuStep: """Same objective and optimizer groups for inexpensive engineering checks."""
def __init__(self, model, optimizer, table, clip): self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip
def __call__(self, indices): self.optimizer.zero_grad(set_to_none=True) tokens, labels = (part[indices] for part in self.table) logits = self.model(tokens) loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss.detach()
def _synchronize(device): if device.type == "cuda": torch.cuda.synchronize(device)
def train(spec, out, source, device="cuda:0"): _validate_spec(spec) _check_source(source) if "frozen_data_sha256" not in spec or "common_evaluation_sha256" not in spec: raise ValueError("Training requires frozen data and common evaluation hashes") out = Path(out) _validate_output(out) out.mkdir(parents=True, exist_ok=True) device = _device_setup(device) started_process = time.perf_counter() world = build_world(spec) digest = data_digest(world) depth_step._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) if spec.get("initial_model_sha256", initial_digest) != initial_digest: raise AssertionError("Frozen initialization differs") lr = torch.tensor(spec["lr"], device=device) if device.type == "cuda": optimizer = make_optimizer(model, lr, spec["weight_decay"]) else: optimizer = torch.optim.AdamW( [ { "params": [p for p in model.parameters() if p.ndim >= 2], "weight_decay": spec["weight_decay"], }, {"params": [p for p in model.parameters() if p.ndim < 2], "weight_decay": 0.0}, ], lr=lr, betas=(0.9, 0.999), eps=1e-8, ) sizes = [len(world[name]) for name in TRAIN_SPLITS] if any(size == 0 for size in sizes): raise ValueError("Do not reroll a world with an empty sampled training stratum") packed = [ pack_rows(world[name], separator=world["metadata"]["separator_token"]) for name in TRAIN_SPLITS ] 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] if device.type == "cuda": graph = FullTokenStep( model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0) ) else: graph = _CpuStep(model, optimizer, table, 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", **dict(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) if device.type == "cuda" else None, "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() endpoint = history[0] for end in spec["nodes"][1:]: _synchronize(device) 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 _synchronize(device) 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", **dict(zip(TRAIN_SPLITS, counts, strict=True))) result = { "spec": spec, "source": source, "data_sha256": digest, "common_evaluation_sha256": world["metadata"]["common_evaluation_sha256"], "initial_model_sha256": initial_digest, "checkpoint_sha256": file_hash(out / "latest.pt"), "finished_utc": utc(), "parameters": sum(p.numel() for p in model.parameters()), "architecture": "loop" if spec["repeats"] > 1 else "standard", "effective_depth": spec["layers"] * spec["repeats"], "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, "device": str(device), "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, "tf32": device.type == "cuda", }, } write_json(out / "complete.json", result) return result
def audit(out, device="cuda:0"): out = Path(out) if (out / "audit.json").exists(): raise FileExistsError(out / "audit.json") device = _device_setup(device) 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 result["common_evaluation_sha256"] != common_evaluation_digest(world): raise AssertionError("Common evaluation identity differs") 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: if set(actual.files) != set(TRAIN_SPLITS): raise AssertionError("Exposure strata differ") for name, count in zip(TRAIN_SPLITS, counts, strict=True): np.testing.assert_array_equal(actual[name], count) row = by_node[node] if row["supervised_tokens"] != node * 832 or row["padded_input_tokens"] != node * 1024: raise AssertionError("Token accounting differs") 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, "nested_support_and_common_pools_checked": 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 checked123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687"""Full-Qwen, nested compositional support with matched atomic supervision."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport platformimport shutilimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Fimport transformersfrom transformers import AutoModelForCausalLM, AutoTokenizer
from . import small_lm_composition as base
FIRST = ("mentor", "advisor")SECOND = ("live", "birth")STRICT_CITIES = ( "Athens Prague Havana Tunis Perth Zurich Bristol Munich " "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw").split()ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1")
def sha(path): digest = hashlib.sha256() with Path(path).open("rb") as handle: for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def write(path, value): base.write(path, value)
def build_world(seed): rng = np.random.default_rng(seed) first_names = ( "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" ).split() names = [ f"{a} {b}" for a in first_names for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() ] names = rng.permutation(names).tolist() atoms, chains = [], [] for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] mappings = [rng.permutation(16).tolist()] mappings.append(np.roll(mappings[0], int(rng.integers(1, 16))).tolist()) city_maps = [rng.permutation(cities).tolist()] city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) ids = {} for j, head in enumerate(heads): for r, relation in enumerate(FIRST): atom = dict( id=len(atoms), pool=pool, role="first", subject=head, relation=relation, answer=bridges[mappings[r][j]], ) atoms.append(atom) ids["first", j, r] = atom["id"] for j, bridge in enumerate(bridges): for s, relation in enumerate(SECOND): atom = dict( id=len(atoms), pool=pool, role="second", subject=bridge, relation=relation, answer=city_maps[s][j], ) atoms.append(atom) ids["second", j, s] = atom["id"] for j, head in enumerate(heads): for r, first in enumerate(FIRST): for s, second in enumerate(SECOND): bridge_index = mappings[r][j] chains.append( dict( id=len(chains), pool=pool, head_index=j, head=head, bridge=bridges[bridge_index], first=first, second=second, answer=city_maps[s][bridge_index], atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], split="strict" if pool == "strict" else ("support" if r == s else "heldout"), ) ) return dict( seed=seed, atoms=atoms, chains=chains, high_support=[c["id"] for c in chains if c["split"] == "support"], low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], )
def question(row, variant=0, atomic=False): if atomic: subject, relation = row["subject"], row["relation"] if row["role"] == "first": templates = ( "Who is {subject}'s {relation}?", "Who is the {relation} of {subject}?", "Name the {relation} of {subject}.", "Give the name of {subject}'s {relation}.", "Give the name of the person serving as {subject}'s {relation}.", ) elif relation == "live": templates = ( "Which city does {subject} live in?", "What city is {subject}'s home?", "Where does {subject} live?", "Name the city where {subject} lives.", "In which city is {subject} living?", ) else: templates = ( "Which city was {subject} born in?", "What is {subject}'s birth city?", "Where was {subject} born?", "Name the city where {subject} was born.", "In which city did {subject}'s birth take place?", ) return templates[variant].format(subject=subject, relation=relation) subject = row["head"] relation = row["first"] if row["second"] == "live": templates = ( "Which city does {subject}'s {relation} live in?", "What city is home to {subject}'s {relation}?", "Where does the {relation} of {subject} live?", "Name the city where {subject}'s {relation} lives.", "In which city is the person serving as {subject}'s {relation} living?", ) else: templates = ( "Which city was {subject}'s {relation} born in?", "What is the birth city of {subject}'s {relation}?", "Where was the {relation} of {subject} born?", "Name the city where {subject}'s {relation} was born.", "In which city did the birth of {subject}'s {relation} take place?", ) return templates[variant].format(subject=subject, relation=relation)
def prompt(row, variant=0, atomic=False): return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:"
def record(tokenizer, row, variant, atomic): # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. ids = tokenizer.encode( prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False ) + [tokenizer.eos_token_id] return dict( ids=ids, labels=[-100, *ids[1:]], id=row["id"], kind="atomic" if atomic else "composition", variant=variant, )
def streams(world, cfg): rng = np.random.default_rng(cfg["training_seed"]) atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} batches = {a: [] for a in cfg["arms"]} for _ in range(cfg["steps"]): if len(atomic_order) < cfg["atomic_per_step"]: atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) atomic = [ [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) ] variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() for arm in cfg["arms"]: support = world[arm + "_support"] if len(comp_order[arm]) < cfg["compositions_per_step"]: comp_order[arm].extend(rng.permutation(support).tolist()) comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] batches[arm].append(dict(atomic=atomic, composition=comp)) return batches
def records(tokenizer, world): return { kind: { (r["id"], v): record(tokenizer, r, v, kind == "atomic") for r in world["atoms" if kind == "atomic" else "chains"] for v in range(4) } for kind in ("atomic", "composition") }
def docs_for(rec, batch): return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]]
def audit(world, batches, rec): assert ( len(world["atoms"]) == 128 and len(world["high_support"]) == 32 and len(world["low_support"]) == 8 ) assert set(world["low_support"]) < set(world["high_support"]) familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} assert covered == familiar_atoms strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} assert not covered & strict_atoms support = [world["chains"][i] for i in world["high_support"]] heldout = [c for c in world["chains"] if c["split"] == "heldout"] strict = [c for c in world["chains"] if c["split"] == "strict"] assert len(heldout) == 32 and len(strict) == 64 # No alternate trained query gives the same head/answer endpoint as a held-out chain. assert not {(c["head"], c["answer"]) for c in support} & { (c["head"], c["answer"]) for c in heldout }
def people(pool): return {a["subject"] for a in world["atoms"] if a["pool"] == pool}
assert not people("familiar") & people("strict") assert not {c["answer"] for c in support} & {c["answer"] for c in strict} budgets, exposure = {}, {} for arm, stream in batches.items(): budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() for batch in stream: docs = docs_for(rec, batch) width = max(len(d["ids"]) for d in docs) budget.update( input_tokens=sum(len(d["ids"]) for d in docs), supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), padded_tokens=len(docs) * width, attention_cells=len(docs) * width**2, ) atomic_counts.update(i for i, _ in batch["atomic"]) comp_counts.update(i for i, _ in batch["composition"]) assert set(comp_counts) <= set(world[arm + "_support"]) budgets[arm] = dict(budget) exposure[arm] = dict( atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) ) if "low" in batches and "high" in batches: assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] assert exposure["low"]["atomic"] == exposure["high"]["atomic"] return dict( status="passed", budgets=budgets, exposures=exposure, familiar_fact_role_coverage_high=len(covered), familiar_fact_role_coverage_low=len( {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} ), heldout_queries=len(heldout), strict_queries=len(strict), target_endpoint_leakage=0, exact_common_atomic_sequence=True, exact_atomic_stream_loss_weight=True, composition_slots_equal=True, )
def freeze(config_path): cfg = base.read(config_path) art = Path(cfg["artifact_root"]) assert not (art / "lock.json").exists(), "Preserve frozen batch." tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) sources = [ str(config_path), "src/llm_memory_editability/natural_composition_confirmation.py", "src/llm_memory_editability/small_lm_composition.py", "scripts/run_natural_composition_confirmation.py", "tests/test_natural_composition_confirmation.py", "docs/development-artifacts/natural-composition-confirmation-v1/design.md", ] source_hashes = {} for source in sources: dest = art / "source" / source dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, dest) source_hashes[source] = sha(source) data_files = {} for seed in cfg["world_seeds"]: world = build_world(seed) batch = streams(world, cfg) report = audit(world, batch, records(tokenizer, world)) for filename, obj in ( ("world.json", world), ("streams.json", batch), ("data-audit.json", report), ): path = art / f"w{seed}" / filename write(path, obj) data_files[str(path)] = sha(path) model_files = { str(p): sha(p) for p in Path(cfg["model_path"]).iterdir() if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") } write( art / "environment.json", dict( python=platform.python_version(), executable=str(Path(__import__("sys").executable)), torch=torch.__version__, transformers=transformers.__version__, gpu_inventory=__import__("subprocess").check_output( ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], text=True, ), ), ) write( art / "lock.json", dict( status="locked_before_training", utc=base.now(), sources=source_hashes, data_files=data_files, model_files=model_files, config=cfg, ), ) print( json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True )
def check_lock(cfg): lock = base.read(Path(cfg["artifact_root"]) / "lock.json") for group in ("sources", "data_files", "model_files"): for path, digest in lock[group].items(): assert sha(path) == digest, path
def evaluation_rows(world, extras=False): rows = [] for view in (0, 4) if extras else (0,): for atom in world["atoms"]: rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) for chain in world["chains"]: rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) return rows
@torch.inference_mode()def generate(model, tokenizer, rows, cfg): model.eval() tokenizer.padding_side = "left" output = [] for start in range(0, len(rows), cfg["eval_batch"]): chunk = rows[start : start + cfg["eval_batch"]] inputs = tokenizer( [r["prompt"] for r in chunk], padding=True, return_tensors="pt", add_special_tokens=False, ).to(cfg["device"]) with torch.autocast("cuda", dtype=torch.bfloat16): tokens = model.generate( **inputs, do_sample=False, max_new_tokens=cfg["max_new_tokens"], pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, use_cache=True, )[:, inputs.input_ids.shape[1] :] for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): if tokenizer.eos_token_id in tok: tok = tok[: tok.index(tokenizer.eos_token_id) + 1] text = tokenizer.decode(tok, skip_special_tokens=True) output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) return output
def evaluate(model, tokenizer, world, cfg, extras=False): direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) if not extras: return direct atoms = {a["id"]: a for a in world["atoms"]} lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} second_calls = [] for row in direct: if row["mode"] != "direct": continue first = lookup[row["atom_ids"][0], row["view"]] generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) second_calls.append( dict( row, mode="autonomous", prompt=prompt(second, row["view"], True), generated_bridge=generated_bridge, first_tokens=first["tokens"], first_correct=first["correct"], ) ) return direct + generate(model, tokenizer, second_calls, cfg)
def metrics(rows, world, arm): result = {} for view in sorted({r["view"] for r in rows}): atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} for pool in ("familiar", "strict"): for role in ("first", "second"): selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] result[f"v{view}_{pool}_{role}"] = dict( correct=sum(r["correct"] for r in selected), n=len(selected) ) for split in ("heldout", "strict", "training"): ids = ( set(world[arm + "_support"]) if split == "training" else {c["id"] for c in world["chains"] if c["split"] == split} ) for mode in ("direct", "autonomous"): selected = [ r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids ] if selected: result[f"v{view}_{split}_{mode}"] = dict( correct=sum(r["correct"] for r in selected), n=len(selected) ) mastered = [ r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) ] result[f"v{view}_{split}_{mode}_both_atomic"] = dict( correct=sum(r["correct"] for r in mastered), n=len(mastered), full_n=len(selected), ) return result
def stream_loss(model, inputs, atomic_count, atomic_weight): logits = model( input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False ).logits[:, :-1] labels = inputs["labels"][:, 1:] losses = F.cross_entropy( logits.float().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none", ignore_index=-100, ).reshape_as(labels) atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() return atomic_weight * atomic + (1 - atomic_weight) * comp
def run(config_path, seed, arm): cfg = base.read(config_path) check_lock(cfg) assert seed in cfg["world_seeds"] and arm in cfg["arms"] art = Path(cfg["artifact_root"]) / f"w{seed}" out = Path(cfg["output_root"]) / f"w{seed}-{arm}" assert not (out / "status.json").exists(), "Preserve existing execution." world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] write(out / "status.json", dict(status="running", utc=base.now())) started = time.perf_counter() torch.set_num_threads(cfg["cpu_threads"]) torch.manual_seed(cfg["training_seed"]) torch.cuda.set_device(cfg["device"]) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.cuda.reset_peak_memory_stats() tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) tokenizer.pad_token = tokenizer.eos_token
def load(path): return AutoModelForCausalLM.from_pretrained( path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True ).to(cfg["device"])
model = load(cfg["model_path"]) assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 assert len({id(layer.mlp) for layer in model.model.layers}) == 28 model.requires_grad_(True) samples = base.parameter_samples(model) parameter_count = sum(p.numel() for p in model.parameters()) rec = records(tokenizer, world) optimizer = torch.optim.AdamW( model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True ) curve, budget, train_seconds = [], Counter(), 0.0 for step in range(cfg["steps"] + 1): if step in cfg["nodes"]: rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) write(out / f"predictions-{step:05d}.json", rows) point = dict(step=step, metrics=metrics(rows, world, arm)) curve.append(point) write(out / "curve.json", curve) print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) if step == cfg["steps"]: break decay = 0.5 * ( 1 + math.cos( math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) ) ) lr = ( cfg["minimum_learning_rate"] + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay ) * min(1.0, (step + 1) / cfg["warmup_steps"]) for group in optimizer.param_groups: group["lr"] = lr docs = docs_for(rec, batches[step]) width = max(len(d["ids"]) for d in docs) budget.update( input_tokens=sum(len(d["ids"]) for d in docs), supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), padded_tokens=len(docs) * width, attention_cells=len(docs) * width**2, ) inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) model.train() torch.cuda.synchronize() tick = time.perf_counter() optimizer.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16): loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) assert torch.isfinite(loss) loss.backward() if step == 0: assert all( p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters() ) torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) optimizer.step() torch.cuda.synchronize() train_seconds += time.perf_counter() - tick if (step + 1) % 64 == 0: print( json.dumps( dict( seed=seed, arm=arm, step=step + 1, loss=float(loss.detach()), train_seconds=train_seconds, ) ), flush=True, ) changed = { name: not torch.equal(before, base.parameter_samples(model)[name]) for name, before in samples.items() } assert all(changed.values()) model.save_pretrained(out / "model", safe_serialization=True) tokenizer.save_pretrained(out / "model") architecture = model.config.to_dict() final_rows = rows del optimizer, model, samples, inputs, loss torch.cuda.empty_cache() again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] write( out / "reload-audit.json", dict( status="passed", predictions=len(again), exact_generated_tokens=True, exact_autonomous_prompts=True, ), ) assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] query_width = architecture["num_attention_heads"] * architecture["head_dim"] kv = architecture["num_key_value_heads"] * architecture["head_dim"] per_token = ( layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + d * architecture["vocab_size"] ) flops = ( 6 * per_token * budget["padded_tokens"] + 12 * layers * query_width * budget["attention_cells"] ) summary = dict( status="complete", phase=cfg["phase"], utc=base.now(), world_seed=seed, arm=arm, metrics=metrics(final_rows, world, arm), updates=cfg["steps"], budget=dict(budget), train_seconds=train_seconds, process_seconds=time.perf_counter() - started, estimated_training_matrix_flops=flops, peak_gpu_bytes=torch.cuda.max_memory_allocated(), parameter_count=parameter_count, sampled_parameters_changed=changed, torch_version=torch.__version__, transformers_version=transformers.__version__, gpu=torch.cuda.get_device_name(), tf32=False, lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, ) write(out / "summary.json", summary) write(out / "status.json", dict(status="complete", utc=base.now())) print(json.dumps(summary), flush=True)
def report(config_path): cfg = base.read(config_path) check_lock(cfg) runs, checks = {}, 0 for seed in cfg["world_seeds"]: world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") for arm in cfg["arms"]: out = Path(cfg["output_root"]) / f"w{seed}-{arm}" summary = base.read(out / "summary.json") assert base.read(out / "reload-audit.json")["status"] == "passed" for point in base.read(out / "curve.json"): rows = base.read(out / f"predictions-{point['step']:05d}.json") assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) assert point["metrics"] == metrics(rows, world, arm) checks += len(rows) assert summary["metrics"] == metrics(rows, world, arm) runs[f"w{seed}-{arm}"] = summary differences = {} if len(cfg["arms"]) == 2: for seed in cfg["world_seeds"]: diff = {} for key in runs[f"w{seed}-high"]["metrics"]: high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] if key.endswith("both_atomic") or "training" in key: continue diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] differences[str(seed)] = diff write( Path(cfg["artifact_root"]) / "summary.json", dict( status="complete", phase=cfg["phase"], independent_worlds=len(cfg["world_seeds"]), training_initializations=1, runs=runs, per_world_high_minus_low=differences, independent_node_prediction_checks=checks, total_updates=sum(r["updates"] for r in runs.values()), total_train_seconds=sum(r["train_seconds"] for r in runs.values()), total_process_seconds=sum(r["process_seconds"] for r in runs.values()), ), )
def main(): parser = argparse.ArgumentParser() parser.add_argument("action", choices=("freeze", "run", "report")) parser.add_argument("--config", required=True) parser.add_argument("--world", type=int) parser.add_argument("--arm", choices=("low", "high")) args = parser.parse_args() if args.action == "run": run(args.config, args.world, args.arm) elif args.action == "freeze": freeze(args.config) else: report(args.config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687"""Full-Qwen, nested compositional support with matched atomic supervision."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport platformimport shutilimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Fimport transformersfrom transformers import AutoModelForCausalLM, AutoTokenizer
from . import small_lm_composition as base
FIRST = ("mentor", "advisor")SECOND = ("live", "birth")STRICT_CITIES = ( "Athens Prague Havana Tunis Perth Zurich Bristol Munich " "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw").split()ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1")
def sha(path): digest = hashlib.sha256() with Path(path).open("rb") as handle: for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def write(path, value): base.write(path, value)
def build_world(seed): rng = np.random.default_rng(seed) first_names = ( "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" ).split() names = [ f"{a} {b}" for a in first_names for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() ] names = rng.permutation(names).tolist() atoms, chains = [], [] for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] mappings = [rng.permutation(16).tolist()] mappings.append(np.roll(mappings[0], int(rng.choice(np.arange(2, 16, 2)))).tolist()) city_maps = [rng.permutation(cities).tolist()] city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) ids = {} for j, head in enumerate(heads): for r, relation in enumerate(FIRST): atom = dict( id=len(atoms), pool=pool, role="first", subject=head, relation=relation, answer=bridges[mappings[r][j]], ) atoms.append(atom) ids["first", j, r] = atom["id"] for j, bridge in enumerate(bridges): for s, relation in enumerate(SECOND): atom = dict( id=len(atoms), pool=pool, role="second", subject=bridge, relation=relation, answer=city_maps[s][j], ) atoms.append(atom) ids["second", j, s] = atom["id"] for j, head in enumerate(heads): for r, first in enumerate(FIRST): for s, second in enumerate(SECOND): bridge_index = mappings[r][j] chains.append( dict( id=len(chains), pool=pool, head_index=j, head=head, bridge=bridges[bridge_index], first=first, second=second, answer=city_maps[s][bridge_index], atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], split="strict" if pool == "strict" else ("support" if s == (r ^ (j % 2)) else "heldout"), ) ) return dict( seed=seed, atoms=atoms, chains=chains, high_support=[c["id"] for c in chains if c["split"] == "support"], low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], )
def question(row, variant=0, atomic=False): if atomic: subject, relation = row["subject"], row["relation"] if row["role"] == "first": templates = ( "Who is {subject}'s {relation}?", "Who is the {relation} of {subject}?", "Name the {relation} of {subject}.", "Give the name of {subject}'s {relation}.", "Give the name of the person serving as {subject}'s {relation}.", ) elif relation == "live": templates = ( "Which city does {subject} live in?", "What city is {subject}'s home?", "Where does {subject} live?", "Name the city where {subject} lives.", "In which city is {subject} living?", ) else: templates = ( "Which city was {subject} born in?", "What is {subject}'s birth city?", "Where was {subject} born?", "Name the city where {subject} was born.", "In which city did {subject}'s birth take place?", ) return templates[variant].format(subject=subject, relation=relation) subject = row["head"] relation = row["first"] if row["second"] == "live": templates = ( "Which city does {subject}'s {relation} live in?", "What city is home to {subject}'s {relation}?", "Where does the {relation} of {subject} live?", "Name the city where {subject}'s {relation} lives.", "In which city is the person serving as {subject}'s {relation} living?", ) else: templates = ( "Which city was {subject}'s {relation} born in?", "What is the birth city of {subject}'s {relation}?", "Where was the {relation} of {subject} born?", "Name the city where {subject}'s {relation} was born.", "In which city did the birth of {subject}'s {relation} take place?", ) return templates[variant].format(subject=subject, relation=relation)
def prompt(row, variant=0, atomic=False): return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:"
def record(tokenizer, row, variant, atomic): # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. ids = tokenizer.encode( prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False ) + [tokenizer.eos_token_id] return dict( ids=ids, labels=[-100, *ids[1:]], id=row["id"], kind="atomic" if atomic else "composition", variant=variant, )
def streams(world, cfg): rng = np.random.default_rng(cfg["training_seed"]) atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} batches = {a: [] for a in cfg["arms"]} for _ in range(cfg["steps"]): if len(atomic_order) < cfg["atomic_per_step"]: atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) atomic = [ [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) ] variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() for arm in cfg["arms"]: support = world[arm + "_support"] if len(comp_order[arm]) < cfg["compositions_per_step"]: comp_order[arm].extend(rng.permutation(support).tolist()) comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] batches[arm].append(dict(atomic=atomic, composition=comp)) return batches
def records(tokenizer, world): return { kind: { (r["id"], v): record(tokenizer, r, v, kind == "atomic") for r in world["atoms" if kind == "atomic" else "chains"] for v in range(4) } for kind in ("atomic", "composition") }
def docs_for(rec, batch): return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]]
def audit(world, batches, rec): assert ( len(world["atoms"]) == 128 and len(world["high_support"]) == 32 and len(world["low_support"]) == 8 ) assert set(world["low_support"]) < set(world["high_support"]) familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} assert covered == familiar_atoms strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} assert not covered & strict_atoms support = [world["chains"][i] for i in world["high_support"]] heldout = [c for c in world["chains"] if c["split"] == "heldout"] strict = [c for c in world["chains"] if c["split"] == "strict"] assert len(heldout) == 32 and len(strict) == 64 # No alternate trained query gives the same head/answer endpoint as a held-out chain. assert not {(c["head"], c["answer"]) for c in support} & { (c["head"], c["answer"]) for c in heldout }
def people(pool): return {a["subject"] for a in world["atoms"] if a["pool"] == pool}
assert not people("familiar") & people("strict") assert not {c["answer"] for c in support} & {c["answer"] for c in strict} budgets, exposure = {}, {} for arm, stream in batches.items(): budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() for batch in stream: docs = docs_for(rec, batch) width = max(len(d["ids"]) for d in docs) budget.update( input_tokens=sum(len(d["ids"]) for d in docs), supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), padded_tokens=len(docs) * width, attention_cells=len(docs) * width**2, ) atomic_counts.update(i for i, _ in batch["atomic"]) comp_counts.update(i for i, _ in batch["composition"]) assert set(comp_counts) <= set(world[arm + "_support"]) budgets[arm] = dict(budget) exposure[arm] = dict( atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) ) if "low" in batches and "high" in batches: assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] assert exposure["low"]["atomic"] == exposure["high"]["atomic"] return dict( status="passed", budgets=budgets, exposures=exposure, familiar_fact_role_coverage_high=len(covered), familiar_fact_role_coverage_low=len( {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} ), heldout_queries=len(heldout), strict_queries=len(strict), target_endpoint_leakage=0, exact_common_atomic_sequence=True, exact_atomic_stream_loss_weight=True, composition_slots_equal=True, )
def freeze(config_path): cfg = base.read(config_path) art = Path(cfg["artifact_root"]) assert not (art / "lock.json").exists(), "Preserve frozen batch." tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) sources = [ str(config_path), "src/llm_memory_editability/natural_composition_confirmation_v2.py", "src/llm_memory_editability/small_lm_composition.py", "scripts/run_natural_composition_confirmation_v2.py", "tests/test_natural_composition_confirmation_v2.py", "docs/development-artifacts/natural-composition-confirmation-v1/amendment-v2.md", ] source_hashes = {} for source in sources: dest = art / "source" / source dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, dest) source_hashes[source] = sha(source) data_files = {} for seed in cfg["world_seeds"]: world = build_world(seed) batch = streams(world, cfg) report = audit(world, batch, records(tokenizer, world)) for filename, obj in ( ("world.json", world), ("streams.json", batch), ("data-audit.json", report), ): path = art / f"w{seed}" / filename write(path, obj) data_files[str(path)] = sha(path) model_files = { str(p): sha(p) for p in Path(cfg["model_path"]).iterdir() if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") } write( art / "environment.json", dict( python=platform.python_version(), executable=str(Path(__import__("sys").executable)), torch=torch.__version__, transformers=transformers.__version__, gpu_inventory=__import__("subprocess").check_output( ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], text=True, ), ), ) write( art / "lock.json", dict( status="locked_before_training", utc=base.now(), sources=source_hashes, data_files=data_files, model_files=model_files, config=cfg, ), ) print( json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True )
def check_lock(cfg): lock = base.read(Path(cfg["artifact_root"]) / "lock.json") for group in ("sources", "data_files", "model_files"): for path, digest in lock[group].items(): assert sha(path) == digest, path
def evaluation_rows(world, extras=False): rows = [] for view in (0, 4) if extras else (0,): for atom in world["atoms"]: rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) for chain in world["chains"]: rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) return rows
@torch.inference_mode()def generate(model, tokenizer, rows, cfg): model.eval() tokenizer.padding_side = "left" output = [] for start in range(0, len(rows), cfg["eval_batch"]): chunk = rows[start : start + cfg["eval_batch"]] inputs = tokenizer( [r["prompt"] for r in chunk], padding=True, return_tensors="pt", add_special_tokens=False, ).to(cfg["device"]) with torch.autocast("cuda", dtype=torch.bfloat16): tokens = model.generate( **inputs, do_sample=False, max_new_tokens=cfg["max_new_tokens"], pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, use_cache=True, )[:, inputs.input_ids.shape[1] :] for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): if tokenizer.eos_token_id in tok: tok = tok[: tok.index(tokenizer.eos_token_id) + 1] text = tokenizer.decode(tok, skip_special_tokens=True) output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) return output
def evaluate(model, tokenizer, world, cfg, extras=False): direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) if not extras: return direct atoms = {a["id"]: a for a in world["atoms"]} lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} second_calls = [] for row in direct: if row["mode"] != "direct": continue first = lookup[row["atom_ids"][0], row["view"]] generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) second_calls.append( dict( row, mode="autonomous", prompt=prompt(second, row["view"], True), generated_bridge=generated_bridge, first_tokens=first["tokens"], first_correct=first["correct"], ) ) return direct + generate(model, tokenizer, second_calls, cfg)
def metrics(rows, world, arm): result = {} for view in sorted({r["view"] for r in rows}): atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} for pool in ("familiar", "strict"): for role in ("first", "second"): selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] result[f"v{view}_{pool}_{role}"] = dict( correct=sum(r["correct"] for r in selected), n=len(selected) ) for split in ("heldout", "strict", "training"): ids = ( set(world[arm + "_support"]) if split == "training" else {c["id"] for c in world["chains"] if c["split"] == split} ) for mode in ("direct", "autonomous"): selected = [ r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids ] if selected: result[f"v{view}_{split}_{mode}"] = dict( correct=sum(r["correct"] for r in selected), n=len(selected) ) mastered = [ r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) ] result[f"v{view}_{split}_{mode}_both_atomic"] = dict( correct=sum(r["correct"] for r in mastered), n=len(mastered), full_n=len(selected), ) return result
def stream_loss(model, inputs, atomic_count, atomic_weight): logits = model( input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False ).logits[:, :-1] labels = inputs["labels"][:, 1:] losses = F.cross_entropy( logits.float().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none", ignore_index=-100, ).reshape_as(labels) atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() return atomic_weight * atomic + (1 - atomic_weight) * comp
def run(config_path, seed, arm): cfg = base.read(config_path) check_lock(cfg) assert seed in cfg["world_seeds"] and arm in cfg["arms"] art = Path(cfg["artifact_root"]) / f"w{seed}" out = Path(cfg["output_root"]) / f"w{seed}-{arm}" assert not (out / "status.json").exists(), "Preserve existing execution." world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] write(out / "status.json", dict(status="running", utc=base.now())) started = time.perf_counter() torch.set_num_threads(cfg["cpu_threads"]) torch.manual_seed(cfg["training_seed"]) torch.cuda.set_device(cfg["device"]) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.cuda.reset_peak_memory_stats() tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) tokenizer.pad_token = tokenizer.eos_token
def load(path): return AutoModelForCausalLM.from_pretrained( path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True ).to(cfg["device"])
model = load(cfg["model_path"]) assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 assert len({id(layer.mlp) for layer in model.model.layers}) == 28 model.requires_grad_(True) samples = base.parameter_samples(model) parameter_count = sum(p.numel() for p in model.parameters()) rec = records(tokenizer, world) optimizer = torch.optim.AdamW( model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True ) curve, budget, train_seconds = [], Counter(), 0.0 for step in range(cfg["steps"] + 1): if step in cfg["nodes"]: rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) write(out / f"predictions-{step:05d}.json", rows) point = dict(step=step, metrics=metrics(rows, world, arm)) curve.append(point) write(out / "curve.json", curve) print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) if step == cfg["steps"]: break decay = 0.5 * ( 1 + math.cos( math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) ) ) lr = ( cfg["minimum_learning_rate"] + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay ) * min(1.0, (step + 1) / cfg["warmup_steps"]) for group in optimizer.param_groups: group["lr"] = lr docs = docs_for(rec, batches[step]) width = max(len(d["ids"]) for d in docs) budget.update( input_tokens=sum(len(d["ids"]) for d in docs), supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), padded_tokens=len(docs) * width, attention_cells=len(docs) * width**2, ) inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) model.train() torch.cuda.synchronize() tick = time.perf_counter() optimizer.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16): loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) assert torch.isfinite(loss) loss.backward() if step == 0: assert all( p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters() ) torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) optimizer.step() torch.cuda.synchronize() train_seconds += time.perf_counter() - tick if (step + 1) % 64 == 0: print( json.dumps( dict( seed=seed, arm=arm, step=step + 1, loss=float(loss.detach()), train_seconds=train_seconds, ) ), flush=True, ) changed = { name: not torch.equal(before, base.parameter_samples(model)[name]) for name, before in samples.items() } assert all(changed.values()) model.save_pretrained(out / "model", safe_serialization=True) tokenizer.save_pretrained(out / "model") architecture = model.config.to_dict() final_rows = rows del optimizer, model, samples, inputs, loss torch.cuda.empty_cache() again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] write( out / "reload-audit.json", dict( status="passed", predictions=len(again), exact_generated_tokens=True, exact_autonomous_prompts=True, ), ) assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] query_width = architecture["num_attention_heads"] * architecture["head_dim"] kv = architecture["num_key_value_heads"] * architecture["head_dim"] per_token = ( layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + d * architecture["vocab_size"] ) flops = ( 6 * per_token * budget["padded_tokens"] + 12 * layers * query_width * budget["attention_cells"] ) summary = dict( status="complete", phase=cfg["phase"], utc=base.now(), world_seed=seed, arm=arm, metrics=metrics(final_rows, world, arm), updates=cfg["steps"], budget=dict(budget), train_seconds=train_seconds, process_seconds=time.perf_counter() - started, estimated_training_matrix_flops=flops, peak_gpu_bytes=torch.cuda.max_memory_allocated(), parameter_count=parameter_count, sampled_parameters_changed=changed, torch_version=torch.__version__, transformers_version=transformers.__version__, gpu=torch.cuda.get_device_name(), tf32=False, lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, ) write(out / "summary.json", summary) write(out / "status.json", dict(status="complete", utc=base.now())) print(json.dumps(summary), flush=True)
def report(config_path): cfg = base.read(config_path) check_lock(cfg) runs, checks = {}, 0 for seed in cfg["world_seeds"]: world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") for arm in cfg["arms"]: out = Path(cfg["output_root"]) / f"w{seed}-{arm}" summary = base.read(out / "summary.json") assert base.read(out / "reload-audit.json")["status"] == "passed" for point in base.read(out / "curve.json"): rows = base.read(out / f"predictions-{point['step']:05d}.json") assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) assert point["metrics"] == metrics(rows, world, arm) checks += len(rows) assert summary["metrics"] == metrics(rows, world, arm) runs[f"w{seed}-{arm}"] = summary differences = {} if len(cfg["arms"]) == 2: for seed in cfg["world_seeds"]: diff = {} for key in runs[f"w{seed}-high"]["metrics"]: high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] if key.endswith("both_atomic") or "training" in key: continue diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] differences[str(seed)] = diff write( Path(cfg["artifact_root"]) / "summary.json", dict( status="complete", phase=cfg["phase"], independent_worlds=len(cfg["world_seeds"]), training_initializations=1, runs=runs, per_world_high_minus_low=differences, independent_node_prediction_checks=checks, total_updates=sum(r["updates"] for r in runs.values()), total_train_seconds=sum(r["train_seconds"] for r in runs.values()), total_process_seconds=sum(r["process_seconds"] for r in runs.values()), ), )
def main(): parser = argparse.ArgumentParser() parser.add_argument("action", choices=("freeze", "run", "report")) parser.add_argument("--config", required=True) parser.add_argument("--world", type=int) parser.add_argument("--arm", choices=("low", "high")) args = parser.parse_args() if args.action == "run": run(args.config, args.world, args.arm) elif args.action == "freeze": freeze(args.config) else: report(args.config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""Controlled nonlinear memory editing with full old-fact replay on CPU.
This measures finite-budget optimization, not minimum representational capacity.The data generator's shared rule does not establish the model's internal mechanism."""
import argparseimport copyimport jsonimport mathimport platformimport statisticsimport subprocessimport timefrom dataclasses import asdict, dataclassfrom pathlib import Path
import numpy as np
try: import torch from torch import nn from torch.nn import functional as Fexcept ModuleNotFoundError as exc: raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc
from .neural_data import make_worldfrom .neural_models import build_model, edit_parameters
@dataclass(frozen=True)class NeuralConfig: model: str = "mlp" seeds: tuple[int, ...] = (0, 1, 2) data_seed: int = 0 entities: int = 24 attributes: int = 8 groups: int = 3 answers: int = 4 width: int = 32 hidden: int = 64 layers: int = 2 heads: int = 4 pretrain_steps: int = 400 edit_steps: int = 100 scratch_steps: int = 400 lr: float = 0.01 retention_weight: float = 1.0 edit_scope: str = "ffn" eval_every: int = 10 success_threshold: float = 0.95 threads: int = 1
def validate(self) -> None: if self.model not in {"mlp", "transformer"} or self.edit_scope not in {"ffn", "all"}: raise ValueError("unsupported model or edit scope") for name in ("pretrain_steps", "edit_steps", "scratch_steps", "eval_every", "threads"): value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"{name} must be a positive integer") if not self.seeds or len(set(self.seeds)) != len(self.seeds): raise ValueError("seeds must be nonempty and unique") if any(isinstance(s, bool) or not isinstance(s, int) or s < 0 for s in self.seeds): raise ValueError("seeds must be nonnegative integers") if not math.isfinite(self.lr) or self.lr <= 0: raise ValueError("lr must be finite and positive") if not math.isfinite(self.retention_weight) or self.retention_weight < 0: raise ValueError("retention_weight must be finite and nonnegative") if not 0 < self.success_threshold <= 1: raise ValueError("success_threshold must be in (0, 1]")
@torch.no_grad()def evaluate(model: nn.Module, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor) -> dict: """Evaluate answers against a target world, separating edits and retained facts.""" model.eval() logits = model(x) if not torch.isfinite(logits).all(): raise ValueError("non-finite model outputs") correct = logits.argmax(dim=-1).eq(y).float() target_logits = logits.gather(1, y[:, None]).squeeze(1) competitors = logits.clone().scatter_(1, y[:, None], float("-inf")).max(dim=1).values margins = target_logits - competitors return { "all_accuracy": correct.mean().item(), "edit_accuracy": correct[mask].mean().item(), "retain_accuracy": correct[~mask].mean().item(), "edit_target_nll": F.cross_entropy(logits[mask], y[mask]).item(), "edit_margin": margins[mask].mean().item(), "retain_margin": margins[~mask].mean().item(), }
def fit( model: nn.Module, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor, *, steps: int, config: NeuralConfig, is_edit: bool = False,) -> dict: """Use a fresh optimizer, fixed steps, and a documented full-batch objective.""" parameters = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.Adam(parameters, lr=config.lr) history = [] first_success = None started = time.perf_counter() for step in range(steps + 1): if step % config.eval_every == 0 or step == steps: metrics = evaluate(model, x, y, mask) history.append({"step": step, **metrics}) if ( first_success is None and min(metrics["edit_accuracy"], metrics["retain_accuracy"]) >= config.success_threshold ): first_success = step if step == steps: break model.train() optimizer.zero_grad(set_to_none=True) logits = model(x) if is_edit: loss = F.cross_entropy(logits[mask], y[mask]) if config.retention_weight: loss = loss + config.retention_weight * F.cross_entropy(logits[~mask], y[~mask]) else: loss = F.cross_entropy(logits, y) if not torch.isfinite(loss): raise ValueError("training diverged to a non-finite loss") loss.backward() optimizer.step() return { "steps": steps, "trainable_parameters": sum(p.numel() for p in parameters), "first_success_step": first_success, "elapsed_seconds": time.perf_counter() - started, "history": history, "objective": "edit_ce + retention_weight * retained_ce" if is_edit else "full_world_ce", }
def _summary(runs: list[dict]) -> dict: eligible = [run for run in runs if run["baseline_quality_passed"]] result = {"eligible_seeds": [run["seed"] for run in eligible], "cases": {}} for name in ("rule", "exception"): result["cases"][name] = {} for metric in ("edit_accuracy", "retain_accuracy"): values = [run["cases"][name]["after"][metric] for run in eligible] result["cases"][name][metric] = { "mean": statistics.mean(values) if values else None, "sample_std": statistics.stdev(values) if len(values) > 1 else None, "n": len(values), } return result
def _revision() -> str | None: """Best-effort source revision; an installed wheel may not have a checkout.""" source_root = Path(__file__).resolve().parents[2] if not (source_root / ".git").exists(): return None try: revision = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=source_root, text=True, stderr=subprocess.DEVNULL ).strip() dirty = subprocess.check_output( ["git", "status", "--porcelain"], cwd=source_root, text=True ).strip() return revision + ("+dirty" if dirty else "") except (OSError, subprocess.CalledProcessError): return None
def run_experiment(config: NeuralConfig) -> dict: config.validate() world = make_world( n_entities=config.entities, n_attributes=config.attributes, n_groups=config.groups, n_answers=config.answers, seed=config.data_seed, ) torch.set_num_threads(config.threads) torch.use_deterministic_algorithms(True) x = torch.as_tensor(world.x, dtype=torch.long) original = torch.as_tensor(world.original, dtype=torch.long) mask = torch.as_tensor(world.edit_mask, dtype=torch.bool) runs = [] for seed in config.seeds: torch.manual_seed(seed) initial = build_model( config.model, config.entities, config.attributes, config.answers, width=config.width, hidden=config.hidden, layers=config.layers, heads=config.heads, ) base = copy.deepcopy(initial) baseline_training = fit( base, x, original, mask, steps=config.pretrain_steps, config=config, ) baseline = evaluate(base, x, original, mask) run = { "seed": seed, "parameter_count": sum(p.numel() for p in base.parameters()), "baseline": baseline, "baseline_quality_passed": min(baseline["edit_accuracy"], baseline["retain_accuracy"]) >= config.success_threshold, "baseline_training": baseline_training, "cases": {}, } for name in ("rule", "exception"): target = torch.as_tensor(getattr(world, name), dtype=torch.long) edited = copy.deepcopy(base) edit_parameters(edited, scope=config.edit_scope) before = evaluate(edited, x, target, mask) edit_training = fit( edited, x, target, mask, steps=config.edit_steps, config=config, is_edit=True, ) scratch = copy.deepcopy(initial) scratch_training = fit( scratch, x, target, mask, steps=config.scratch_steps, config=config, ) run["cases"][name] = { "before": before, "after": evaluate(edited, x, target, mask), "scratch": evaluate(scratch, x, target, mask), "edit_training": edit_training, "scratch_training": scratch_training, } runs.append(run) return { "experiment": "nonlinear_synthetic_memory_editing", "config": asdict(config), "versions": { "python": platform.python_version(), "numpy": np.__version__, "torch": torch.__version__, }, "revision": _revision(), "device": "cpu", "world": world.to_metadata(), "protocol": { "paired_edit_initialization": "identical trained checkpoint; fresh Adam per case", "paired_scratch_initialization": "identical untrained initialization; all parameters", "replay": "all retained facts available; uniform CE within each edit/retain subset", "success": "both edit and retain accuracy >= threshold at evaluation checkpoints", "summary_filter": "only seeds passing baseline threshold on both subsets", "limits": [ "Target surprisal is measured, not matched.", "Generator structure is not a measure of learned neural degrees of freedom.", "Scratch failure at finite budget is not an impossibility result.", "Scratch trains all parameters; FFN-only edit failures may reflect " "a restricted update space.", "No natural-language paraphrases or pretrained LLM are evaluated.", "Cross-platform and cross-version bitwise reproducibility is not guaranteed.", ], }, "runs": runs, "summary": _summary(runs), }
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", choices=("mlp", "transformer"), default="mlp") parser.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) parser.add_argument("--edit-scope", choices=("ffn", "all"), default="ffn") defaults = asdict(NeuralConfig()) for name in ( "data_seed", "entities", "attributes", "groups", "answers", "width", "hidden", "layers", "heads", "pretrain_steps", "edit_steps", "scratch_steps", "eval_every", "threads", ): parser.add_argument("--" + name.replace("_", "-"), type=int, default=defaults[name]) for name in ("lr", "retention_weight", "success_threshold"): parser.add_argument("--" + name.replace("_", "-"), type=float, default=defaults[name]) parser.add_argument("--output", type=Path, help="save the same JSON printed to stdout") args = vars(parser.parse_args(argv)) output = args.pop("output") args["seeds"] = tuple(args["seeds"]) try: report = run_experiment(NeuralConfig(**args)) serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) if output: output.parent.mkdir(parents=True, exist_ok=True) output.write_text(serialized + "\n", encoding="utf-8") except (ValueError, OSError) as exc: parser.error(str(exc)) print(serialized) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Balanced fact-table interventions, defined independently of model training."""
from dataclasses import dataclassfrom typing import Any
import numpy as np
@dataclass(frozen=True)class SyntheticWorld: """All entity/attribute queries and two interventions on identical support."""
x: np.ndarray original: np.ndarray rule: np.ndarray exception: np.ndarray edit_mask: np.ndarray group_ids: np.ndarray n_entities: int n_attributes: int n_groups: int n_answers: int seed: int
def task_exceptions(self, labels: np.ndarray) -> int: """Minimum overrides of a group+attribute table; not neural model degrees of freedom.""" labels = np.asarray(labels) if labels.shape != self.original.shape: raise ValueError("labels must contain one answer per fact") exceptions = 0 for group in range(self.n_groups): for attribute in range(self.n_attributes): cell = labels[(self.group_ids[self.x[:, 0]] == group) & (self.x[:, 1] == attribute)] exceptions += cell.size - int(np.bincount(cell, minlength=self.n_answers).max()) return exceptions
def to_metadata(self) -> dict[str, Any]: """JSON-compatible task diagnostics, available before training or editing.""" return { "n_entities": self.n_entities, "n_attributes": self.n_attributes, "n_groups": self.n_groups, "n_answers": self.n_answers, "seed": self.seed, "n_facts": len(self.x), "n_edited": int(self.edit_mask.sum()), "edited_entities": np.unique(self.x[self.edit_mask, 0]).tolist(), "edited_attributes": np.unique(self.x[self.edit_mask, 1]).tolist(), "matched_controls": [ "edit support", "edited fact count", "entity and attribute coverage", "per-entity target-answer histograms", ], "task_side_group_attribute_exceptions": { name: self.task_exceptions(getattr(self, name)) for name in ("original", "rule", "exception") }, "structure_metric_scope": ( "Minimum label overrides of a deterministic group+attribute answer table. " "This is a task-side generator property, not neural degrees of freedom " "or evidence that a trained network learned these groups." ), }
def make_world( n_entities: int = 24, n_attributes: int = 8, n_groups: int = 3, n_answers: int = 4, seed: int = 0,) -> SyntheticWorld: """Generate balanced labels and conflicting exception patterns in edited group 0.
Entity targets are independently shuffled, conditioned on changing every edited fact. The final row is resampled if all entities happen to share one pattern. Rejection sampling is bounded, including for long attribute tables. """ for name, value in { "n_entities": n_entities, "n_attributes": n_attributes, "n_groups": n_groups, "n_answers": n_answers, "seed": seed, }.items(): if isinstance(value, bool) or not isinstance(value, (int, np.integer)): raise ValueError(f"{name} must be an integer") if value < (0 if name == "seed" else 1): raise ValueError(f"{name} is outside its valid range") n_entities, n_attributes, n_groups, n_answers, seed = map( int, (n_entities, n_attributes, n_groups, n_answers, seed), ) if n_groups < 2: raise ValueError("n_groups must be >= 2 to leave retained facts outside the edit support") if n_entities % n_groups or n_entities // n_groups < 2: raise ValueError("n_entities must be divisible by n_groups, with >= 2 entities per group") if n_answers < 3 or n_attributes % n_answers: raise ValueError("n_answers must be >= 3 and divide n_attributes")
rng = np.random.default_rng(seed) group_ids = np.repeat(np.arange(n_groups), n_entities // n_groups).astype(np.int64) x = np.column_stack( ( np.repeat(np.arange(n_entities), n_attributes), np.tile(np.arange(n_attributes), n_entities), ) ).astype(np.int64) original = (group_ids[x[:, 0]] + x[:, 1]) % n_answers edit_mask = group_ids[x[:, 0]] == 0 rule = original.copy() rule[edit_mask] = (rule[edit_mask] + 1) % n_answers exception = original.copy() # Every edited entity has the same balanced original labels and rule targets. old_row = original[:n_attributes] edited_entities = np.flatnonzero(group_ids == 0) sampled_rows = [] for row_index, entity in enumerate(edited_entities): for _ in range(10_000): candidate = rng.permutation(old_row) shared_pattern = row_index == len(edited_entities) - 1 and all( np.array_equal(row, candidate) for row in sampled_rows ) if np.all(candidate != old_row) and not shared_pattern: sampled_rows.append(candidate) start = entity * n_attributes exception[start : start + n_attributes] = candidate break else: raise ValueError( "Could not sample balanced exception patterns in 10,000 attempts; " "use more answers or fewer attributes to make rejection sampling practical." ) return SyntheticWorld( x, original, rule, exception, edit_mask, group_ids, n_entities, n_attributes, n_groups, n_answers, seed, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""Trainable nonlinear fact models; importing this module requires PyTorch."""
import torchfrom torch import nn
class FactMLP(nn.Module): """Separate entity/attribute embeddings followed by a nonlinear MLP."""
def __init__( self, n_entities: int, n_attributes: int, n_answers: int, width: int, hidden: int, layers: int, ) -> None: super().__init__() self.entity_embedding = nn.Embedding(n_entities, width) self.attribute_embedding = nn.Embedding(n_attributes, width) blocks = [] for layer in range(layers): blocks.extend((nn.Linear(2 * width if layer == 0 else hidden, hidden), nn.GELU())) self.hidden = nn.Sequential(*blocks) self.answer_head = nn.Linear(hidden, n_answers)
def forward(self, facts: torch.Tensor) -> torch.Tensor: _validate_facts(facts) embedded = torch.cat( ( self.entity_embedding(facts[:, 0]), self.attribute_embedding(facts[:, 1]), ), dim=-1, ) return self.answer_head(self.hidden(embedded))
class FactTransformer(nn.Module): """Causal [ENTITY, ATTRIBUTE, QUERY] transformer with an answer classification head."""
def __init__( self, n_entities: int, n_attributes: int, n_answers: int, width: int, hidden: int, layers: int, heads: int, ) -> None: super().__init__() self.n_entities = n_entities self.query_id = n_entities + n_attributes self.token_embedding = nn.Embedding(self.query_id + 1, width) self.position_embedding = nn.Embedding(3, width) encoder_layer = nn.TransformerEncoderLayer( d_model=width, nhead=heads, dim_feedforward=hidden, dropout=0.0, activation="gelu", batch_first=True, norm_first=True, ) self.encoder = nn.TransformerEncoder( encoder_layer, num_layers=layers, norm=nn.LayerNorm(width), enable_nested_tensor=False, ) # TransformerEncoder clones its prototype; initialize each layer independently. for layer in self.encoder.layers: nn.init.xavier_uniform_(layer.self_attn.in_proj_weight) for module in layer.modules(): if isinstance(module, nn.Linear): nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) self.answer_head = nn.Linear(width, n_answers) self.register_buffer("causal_mask", torch.triu(torch.ones(3, 3, dtype=torch.bool), 1))
def forward(self, facts: torch.Tensor) -> torch.Tensor: _validate_facts(facts) tokens = torch.stack( ( facts[:, 0], facts[:, 1] + self.n_entities, torch.full_like(facts[:, 0], self.query_id), ), dim=1, ) embedded = self.token_embedding(tokens) embedded = embedded + self.position_embedding(torch.arange(3, device=facts.device)) encoded = self.encoder(embedded, mask=self.causal_mask) return self.answer_head(encoded[:, -1])
def _validate_facts(facts: torch.Tensor) -> None: if facts.ndim != 2 or facts.shape[1] != 2 or facts.dtype != torch.long: raise ValueError("facts must be an int64 tensor with shape (n_facts, 2)")
def build_model( model_type: str, n_entities: int, n_attributes: int, n_answers: int, width: int = 32, hidden: int = 64, layers: int = 2, heads: int = 4,) -> nn.Module: """Construct an MLP or a causal transformer; initialization uses the torch RNG.""" for name, value in { "n_entities": n_entities, "n_attributes": n_attributes, "n_answers": n_answers, "width": width, "hidden": hidden, "layers": layers, "heads": heads, }.items(): if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{name} must be a positive integer") if model_type == "mlp": return FactMLP(n_entities, n_attributes, n_answers, width, hidden, layers) if model_type == "transformer": if width % heads: raise ValueError("transformer width must be divisible by heads") return FactTransformer(n_entities, n_attributes, n_answers, width, hidden, layers, heads) raise ValueError("model_type must be 'mlp' or 'transformer'")
def edit_parameters(model: nn.Module, scope: str = "ffn") -> list[nn.Parameter]: """Freeze outside the chosen edit scope, returning the exact optimizer parameters.""" if scope not in {"ffn", "all"}: raise ValueError("scope must be 'ffn' or 'all'") if scope == "all": selected = list(model.parameters()) elif isinstance(model, FactMLP): selected = list(model.hidden.parameters()) elif isinstance(model, FactTransformer): selected = [ parameter for layer in model.encoder.layers for linear in (layer.linear1, layer.linear2) for parameter in linear.parameters() ] else: raise ValueError("ffn scope requires a FactMLP or FactTransformer") selected_ids = {id(parameter) for parameter in selected} for parameter in model.parameters(): parameter.requires_grad_(id(parameter) in selected_ids) parameter.grad = None return selected12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Constrained response primitives; empirical scopes are recorded by the runner."""
from __future__ import annotations
import hashlib
import torch
def select_records(records, count, seed, role): """Select before diagnostics, independently of accuracy or measured geometry.""" if len(records) < count: raise ValueError(f"Insufficient records for {role}") return sorted( records, key=lambda row: hashlib.sha256(f"{seed}:{role}:{row['case_id']}".encode()).hexdigest(), )[:count]
def psd_solve(gram, rhs, rtol): values, vectors = torch.linalg.eigh(gram.double()) eligible = values > values.max().clamp_min(1e-30) * rtol projected = vectors[:, eligible].T @ rhs.double() result = vectors[:, eligible] @ (projected / values[eligible]) return result, int(eligible.sum())
def functional_projection(target, keep, rtol): """Orthogonal projection onto the numerical null space of keep gradients.""" g, r = target.double(), keep.double() coefficients, rank = psd_solve(r @ r.T, r @ g, rtol) result = g - coefficients @ r denominator = g.square().sum().clamp_min(1e-30) return result.to(target.dtype), { "rank": rank, "retained_energy": float(result.square().sum() / denominator), "relative_keep_residual": float( (r @ result).norm() / (r.norm() * result.norm()).clamp_min(1e-30) ), }
def feature_basis(features, rtol): """Rows are real token features; right singular vectors span protected keys.""" _, singular, vh = torch.linalg.svd(features.double(), full_matrices=False) selected = singular > singular[0] * rtol return vh[selected], singular
def module_projection(gradient, basis): g = gradient.double() return (g - (g @ basis.T) @ basis).to(gradient.dtype)
def local_gradients(x, up, gate, down_weight, output_derivative): """All-position exact SwiGLU chain rule; no replacement of the forward model.""" sigmoid = torch.sigmoid(gate) activated = gate * sigmoid derivative = sigmoid + gate * sigmoid * (1 - sigmoid) value_derivative = output_derivative @ down_weight return { "down": output_derivative.T @ (up * activated), "up": (value_derivative * activated).T @ x, "gate": (value_derivative * up * derivative).T @ x, }
def route_output(current, original, attention, route): """Forward activation intervention; baseline function is identical at zero update.""" if route == "all": return current mask = torch.zeros_like(attention, dtype=torch.bool) mask[torch.arange(len(mask), device=mask.device), attention.sum(1) - 1] = True if route == "earlier": mask = attention.bool() & ~mask elif route != "last": raise ValueError(route) return torch.where(mask.unsqueeze(-1), current, original)
def update_scale(direction, target_gradient, step, parameter_norm, cap, metric): d_norm = direction.double().norm() g_norm = target_gradient.double().norm() response = target_gradient.double() @ direction.double() if d_norm == 0 or response <= 0: return 0.0, True if metric == "equal_norm": scale = step / (g_norm * d_norm) elif metric == "equal_target": scale = step / response else: raise ValueError(metric) maximum = cap * parameter_norm / d_norm return float(torch.minimum(scale, maximum)), bool(scale > maximum)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416"""Position-routed down updates, complete-answer objectives, and audited data helpers."""
from __future__ import annotations
import hashlibimport jsonimport osimport reimport timefrom datetime import datetime, timezonefrom pathlib import Path
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
import numpy as npimport torchimport torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer
from .hebbian_data import TEMPLATE, encode_answer, score_answerfrom .hebbian_model import set_determinism, tensor_hash
ROOT = Path(__file__).resolve().parents[2]DATA = ROOT / "data/qwen-path-learning-v1"ART = ROOT / "docs/development-artifacts/qwen-path-learning-v1"RESULTS = ROOT / "results/qwen-path-learning-v1"CONFIG = ROOT / "configs/qwen-path-learning-v1.json"GROUPS = ("S_end", "S_other", "C", "W", "L", "A")
# All views ask the same original CounterFact relation; no generated answer labels.RELATIONS = { "P19": ("{} was born in", "The birthplace of {} is", "{}'s birthplace is"), "P20": ("{} died in", "The place of death of {} is", "{}'s place of death is"), "P103": ( "The native language of {} is", "The mother tongue of {} is", "{}'s native language is", ), "P176": ("The manufacturer of {} is", "{} was manufactured by", "{}'s manufacturer is"), "P178": ("The developer of {} is", "{} was developed by", "{}'s developer is"), "P495": ( "The country of origin of {} is", "{} originated in the country of", "{}'s country of origin is", ), "P740": ( "{} was founded in", "The place where {} was founded is", "{}'s place of formation is", ), "P364": ( "The original language of {} is", "{} was originally in the language", "{}'s original language is", ), "P407": ("The language of {} is", "{} is in the language", "{}'s language is"),}
def now(): return datetime.now(timezone.utc).isoformat()
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(f".{os.getpid()}.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 stream: for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): h.update(chunk) return h.hexdigest()
def stable(value): return hashlib.sha256(str(value).encode()).hexdigest()
def encode_fact(tokenizer, subject, statement, answer, view=0, plain=False): prompt = statement if plain else TEMPLATE.format(statement) enc = encode_answer(tokenizer, prompt, answer) offset = 0 if plain else prompt.index(statement) subject_start = statement.index(subject) + offset subject_end = subject_start + len(subject) offsets = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)[ "offset_mapping" ] subject_tokens = [ i for i, (a, b) in enumerate(offsets) if b > subject_start and a < subject_end ] if not subject_tokens: raise ValueError("Subject has no tokens") roles = [] for i, (a, b) in enumerate(offsets): if i == len(offsets) - 1: role = "L" elif i == subject_tokens[-1]: role = "S_end" elif i in subject_tokens: role = "S_other" elif b > offset and a < offset + len(statement): role = "C" else: role = "W" roles.append(role) roles += ["A"] * (len(enc["input_ids"]) - len(roles)) return {**enc, "prompt": prompt, "roles": roles, "view": view, "plain": plain}
def random_positions(roles, group, key, seed, bins=2, draws=16, energies=None): """Disjoint count/bin-matched controls; optional local-energy matching only.""" n = roles.index("L") + 1 target = [i for i, role in enumerate(roles[: n - 1]) if role == group] if not target: return [], {"valid": False, "reason": "empty_group"}
def strata(i): return min(bins - 1, i * bins // max(n - 1, 1))
eligible = { b: [i for i in range(n - 1) if i not in target and strata(i) == b] for b in range(bins) } counts = {b: sum(strata(i) == b for i in target) for b in range(bins)} if any(len(eligible[b]) < counts[b] for b in range(bins)): return [], {"valid": False, "reason": "insufficient_disjoint_positions"} rng = np.random.default_rng(int(stable(f"{key}:{group}:{seed}")[:16], 16)) options = [] for _ in range(draws if energies is not None else 1): positions = sorted( int(i) for b in range(bins) for i in rng.choice(eligible[b], counts[b], replace=False) ) error = ( 0.0 if energies is None else abs(sum(energies[i] for i in positions) - sum(energies[i] for i in target)) / max(sum(energies[i] for i in target), 1e-30) ) options.append((error, positions)) error, selected = min(options, key=lambda x: (x[0], x[1])) return selected, {"valid": True, "relative_energy_error": error, "count": len(target)}
def sequence_mean(values, batch_indices, count): sums = values.new_zeros(count).scatter_add_(0, batch_indices, values) return sums / torch.bincount(batch_indices, minlength=count).clamp_min(1)
def fisher_quadratic(logp, response): p = logp.exp() return 0.5 * ((p * response.square()).sum(-1) - (p * response).sum(-1).square())
class PathEngine: def __init__(self, device, layer=None): self.cfg = read(CONFIG) set_determinism(self.cfg["seed"]) self.device = torch.device(device) self.tokenizer = AutoTokenizer.from_pretrained( ROOT / self.cfg["model_source"], local_files_only=True ) self.tokenizer.pad_token = self.tokenizer.eos_token self.model = ( AutoModelForCausalLM.from_pretrained( ROOT / self.cfg["model_source"], local_files_only=True, dtype=torch.float32, attn_implementation="eager", ) .to(self.device) .eval() .requires_grad_(False) ) self.layer_index = self.cfg["layer"] if layer is None else layer self.down = self.model.model.layers[self.layer_index].mlp.down_proj self.base_hash = tensor_hash(self.down.weight) self.delta = torch.nn.Parameter(torch.zeros_like(self.down.weight)) self.route = "all" self.route_seed = 0 self.route_group = None self.route_positions = {} self.mask = None self.capture = None self.handle = self.down.register_forward_hook(self._hook) self.reference = {} self.forward_tokens = 0 self.started = time.time()
def _hook(self, module, args, output): increment = F.linear(args[0], self.delta) if self.capture is not None: self.capture.append(increment.detach().square().sum(-1).cpu()) if self.mask is not None: increment = increment * self.mask[:, -increment.shape[1] :, None] return output + increment
def mask_for(self, enc): roles = enc["roles"] mask = [1.0] * len(roles) if self.route == "all": return mask if "L" not in roles: # Unannotated natural text has no fact-position groups. return mask if self.route == "group": positions = [i for i, x in enumerate(roles) if x == self.route_group] elif self.route == "random": positions, _ = random_positions(roles, self.route_group, enc["key"], self.route_seed) elif self.route == "positions": positions = self.route_positions.get(enc["key"], []) elif self.route == "zero": positions = list(range(len(roles))) else: raise ValueError(self.route) for i in positions: mask[i] = 0.0 return mask
def batch(self, encoded, prompt_only=False): sequences = [ e["input_ids"][: e["answer_start"]] if prompt_only else e["input_ids"] for e in encoded ] width = max(map(len, sequences)) ids = torch.full( (len(sequences), width), self.tokenizer.pad_token_id, device=self.device, dtype=torch.long, ) attention = torch.zeros_like(ids) loss = torch.zeros_like(ids, dtype=torch.bool) masks = torch.ones_like(ids, dtype=torch.float32) 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: loss[i, : len(seq)] = torch.tensor( enc["loss_mask"], device=self.device, dtype=torch.bool ) masks[i, : len(seq)] = torch.tensor(self.mask_for(enc)[: len(seq)], device=self.device) self.mask = masks return ids, attention, loss
def hidden(self, ids, attention): self.forward_tokens += ids.numel() return self.model.model( input_ids=ids, attention_mask=attention, use_cache=False ).last_hidden_state
def objectives(self, encoded, include_kl=True): ids, attention, mask = self.batch(encoded) b, t = torch.where(mask[:, 1:]) hidden = self.hidden(ids, attention) logits = self.model.lm_head(hidden[b, t]) ce = sequence_mean( F.cross_entropy(logits, ids[b, t + 1], reduction="none"), b, len(encoded) ) if not include_kl: return ce, None with torch.no_grad(): ref_hidden = torch.cat([self.reference[e["key"]] for e in encoded]).to(self.device) ref_log = F.log_softmax(self.model.lm_head(ref_hidden), dim=-1) divergence = (ref_log.exp() * (ref_log - F.log_softmax(logits, dim=-1))).sum(-1) return ce, sequence_mean(divergence, b, len(encoded))
@torch.no_grad() def cache_reference(self, encoded, batch_size=8): if self.delta.count_nonzero().item(): raise ValueError("Reference must be cached at the parent") for start in range(0, len(encoded), batch_size): chunk = encoded[start : start + batch_size] ids, attention, mask = self.batch(chunk) b, t = torch.where(mask[:, 1:]) hidden = self.hidden(ids, attention) for i, enc in enumerate(chunk): self.reference[enc["key"]] = hidden[b[b == i], t[b == i]].detach().cpu()
@torch.no_grad() def generate(self, encoded): # Cached greedy decoding; routing is built from the input prompt alone. sequences = [e["input_ids"][: e["answer_start"]] for e in encoded] width = max(map(len, sequences)) ids = torch.full( (len(sequences), width), self.tokenizer.pad_token_id, device=self.device, dtype=torch.long, ) attention = torch.zeros_like(ids) route_mask = torch.ones_like(ids, dtype=torch.float32) 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 route_mask[i, -len(seq) :] = torch.tensor( self.mask_for(enc)[: len(seq)], device=self.device ) tails = [[] for _ in encoded] done = [False] * len(encoded) cache = None for step in range(self.cfg["max_new_tokens"]): position = attention.cumsum(-1) - 1 position.masked_fill_(attention == 0, 0) self.mask = ( route_mask if step == 0 else torch.full( (len(encoded), 1), 0.0 if self.route == "zero" or (self.route == "group" and self.route_group == "A") else 1.0, device=self.device, ) ) out = self.model.model( input_ids=ids, attention_mask=attention, position_ids=position if step == 0 else position[:, -1:], past_key_values=cache, use_cache=True, ) self.forward_tokens += ids.numel() cache = out.past_key_values next_ids = self.model.lm_head(out.last_hidden_state[:, -1]).argmax(-1) for i, token in enumerate(next_ids.tolist()): if not done[i]: tails[i].append(token) decoded = self.tokenizer.decode(tails[i], skip_special_tokens=True) done[i] = token == self.tokenizer.eos_token_id or "\n" in decoded if all(done): break ids = next_ids[:, None] attention = torch.cat([attention, torch.ones_like(ids)], dim=1) return [ { "prediction": self.tokenizer.decode(tail, skip_special_tokens=True), "tokens": tail, "eos": self.tokenizer.eos_token_id in tail, } for tail in tails ]
@torch.no_grad() def evaluate(self, records, views=(0,), batch_size=16, with_kl=True, generate=True): entries = [(r, r["encoded"][v]) for r in records for v in views] output = [] for start in range(0, len(entries), batch_size): chunk = entries[start : start + batch_size] encs = [e for _, e in chunk] ce, kl = self.objectives(encs, include_kl=with_kl) predictions = self.generate(encs) if generate else [None] * len(chunk) for i, ((record, enc), prediction) in enumerate(zip(chunk, predictions, strict=True)): item = { "case_id": record["case_id"], "view": enc["view"], "ce": float(ce[i]), "kl": None if kl is None else float(kl[i]), } if prediction is not None: item.update(prediction) item["correct"] = score_answer(prediction["prediction"], record["aliases"]) output.append(item) return output
@torch.no_grad() def evaluate_text(self, encoded): result = [] for start in range(0, len(encoded), 2): chunk = encoded[start : start + 2] ce, kl = self.objectives(chunk) result.extend( {"key": e["key"], "ce": float(c), "kl": float(k)} for e, c, k in zip(chunk, ce, kl, strict=True) ) return result
def restore(self): with torch.no_grad(): self.delta.zero_() self.route = "all" self.mask = None assert tensor_hash(self.down.weight) == self.base_hash
def mean(rows, key): return float(np.mean([r[key] for r in rows])) if rows else None
def valid_aliases(raw): by_id = {} for row in raw: target = row["requested_rewrite"]["target_true"] by_id.setdefault(target["id"], set()).add(target["str"].strip()) return {k: sorted(v) for k, v in by_id.items()}
def articles_from_lines(lines): articles = [] title, parts = None, [] for line in lines: if re.fullmatch(r"\s*= [^=]+ =\s*", line): if title and parts: articles.append((title, "".join(parts))) title, parts = line.strip(), [] elif title: parts.append(line) if title and parts: articles.append((title, "".join(parts))) return articles123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627"""Frozen-matrix execution and development-only selection for path learning."""
from __future__ import annotations
import jsonimport osimport platformimport shutilimport time
import numpy as npimport torchimport transformers
from .qwen_path_learning import ( ART, CONFIG, DATA, RESULTS, ROOT, PathEngine, digest, encode_fact, mean, now, random_positions, read, write,)
def preflight(device): from .hebbian_model import aggregate_hash, state_hashes
cfg = read(CONFIG) old_records = read(ROOT / "data/hebbian-learning-v1/pools.json")["B_dev"][:2] engine = PathEngine(device) encs = [] for r in old_records: enc = encode_fact(engine.tokenizer, r["subject"], r["views"][0], r["answer"]) enc["key"] = f"preflight-{r['case_id']}" encs.append(enc) before_hash = aggregate_hash(state_hashes(engine.model)) assert all(not p.requires_grad for p in engine.model.parameters()) assert engine.delta.numel() == 3145728 engine.cache_reference(encs) baseline_ce, zero_kl = engine.objectives(encs) baseline_ce = baseline_ce.detach() checks = { "parameter_count": engine.delta.numel(), "zero_kl_max": float(zero_kl.detach().abs().max()), } assert checks["zero_kl_max"] < 1e-5 for group in cfg["groups"]: engine.route, engine.route_group = "group", group ce, _ = engine.objectives(encs) assert torch.equal(ce.detach(), baseline_ce) engine.route = "all" with torch.no_grad(): engine.delta.normal_(std=1e-5) ids, attention, _ = engine.batch(encs) with torch.no_grad(): separate = engine.hidden(ids, attention) delta = engine.delta.clone() original_weight = engine.down.weight.clone() engine.down.weight.add_(delta) engine.delta.zero_() fused = engine.hidden(ids, attention) engine.down.weight.copy_(original_weight) engine.delta.copy_(delta) checks["all_vs_fused_hidden_max_error"] = float((separate - fused).abs().max()) assert checks["all_vs_fused_hidden_max_error"] < 1e-3 engine.restore() opt = optimizer(engine, 1e-5) begun = time.time() ce, _ = engine.objectives(encs, include_kl=False) ce.mean().backward() checks["delta_gradient_norm"] = float(engine.delta.grad.norm()) torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) opt.step() checks["single_old_episode_step_seconds"] = time.time() - begun assert checks["delta_gradient_norm"] > 0 and torch.isfinite(engine.delta).all() engine.restore() assert aggregate_hash(state_hashes(engine.model)) == before_hash ce, _ = engine.objectives(encs) checks["restore_ce_max_error"] = float((ce.detach() - baseline_ce).abs().max()) assert checks["restore_ce_max_error"] == 0 del engine torch.cuda.empty_cache() final = PathEngine(device, layer=27) with torch.no_grad(): final.delta.normal_(std=1e-4) final.route = "zero" parent_ce, _ = final.objectives(encs, include_kl=False) # Enable only earlier-prompt increments, and disable all readout positions. final.route = "positions" final.route_positions = { e["key"]: list(range(e["answer_start"] - 1, len(e["roles"]))) for e in encs } early_ce, _ = final.objectives(encs, include_kl=False) checks["final_layer_earlier_ce_max_error"] = float((early_ce - parent_ce).abs().max()) assert checks["final_layer_earlier_ce_max_error"] == 0 final.restore() checks["passed"] = True checks["time"] = now() checks["training_cases"] = "two old B_dev facts; no new developmental outcome selection" checks["parent_model_sha256"] = before_hash write(ART / "preflight.json", checks) print(json.dumps(checks), flush=True)
def jobs(): cfg = read(CONFIG) return [ { "id": f"dev-e{episode}-lr{lr:g}-b{beta}", "episode": episode, "lr": lr, "beta": beta, "seed": 0, "phase": "dev", "condition": "ordinary", } for episode in range(4) for lr in cfg["learning_rates"] for beta in cfg["betas_replay"] ]
def sources(): return [ "configs/qwen-path-learning-v1.json", "scripts/run_qwen_path_learning.py", "src/llm_memory_editability/qwen_path_learning.py", "src/llm_memory_editability/qwen_path_train.py", "src/llm_memory_editability/hebbian_data.py", "src/llm_memory_editability/hebbian_model.py", "src/llm_memory_editability/hebbian_learning.py", "tests/test_qwen_path_learning.py", ]
def freeze(): if (ART / "execution-lock.json").exists(): raise RuntimeError("Execution lock exists") assert read(ART / "preflight.json")["passed"] assert read(ART / "selection-lock.json")["selection_sha256"] == digest(DATA / "selection.json") frozen = {} for relative in sources() + [ "docs/hebbian-learning-plan-v1.md", "docs/experimental-protocol.md", ]: path = ROOT / relative target = ART / "execution-source" / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, target) frozen[relative] = digest(path) cfg = read(CONFIG) model = ROOT / cfg["model_source"] / "model.safetensors" write( ART / "execution-lock.json", { "time": now(), "status": "locked_before_development_updates", "sources": frozen, "inputs": { str(p.relative_to(ROOT)): digest(p) for p in [DATA / "selection.json", DATA / "text.json", model] }, "matrix": jobs(), "environment": { "python": platform.python_version(), "torch": torch.__version__, "transformers": transformers.__version__, "numpy": np.__version__, }, "config": cfg, }, )
def check_lock(): lock = read(ART / "execution-lock.json") for relative in sources(): assert digest(ROOT / relative) == lock["sources"][relative], relative for relative in ( "data/qwen-path-learning-v1/selection.json", "data/qwen-path-learning-v1/text.json", ): assert digest(ROOT / relative) == lock["inputs"][relative]
def optimizer(engine, lr): cfg = engine.cfg["optimizer"] return torch.optim.AdamW( [engine.delta], lr=lr, betas=tuple(cfg["betas"]), eps=cfg["eps"], weight_decay=cfg["weight_decay"], )
def schedule(cfg, episode, seed, n_r=64, n_text=64): rng = np.random.default_rng(cfg["seed"] + 1000 * episode + seed) # Fixed cyclic shuffled decks give exactly equal aggregate exposure across jobs. replay, text = rng.permutation(n_r), rng.permutation(n_text) return [ { "R": [int(replay[(step * 8 + i) % n_r]) for i in range(8)], "text": [int(text[(step * 2 + i) % n_text]) for i in range(2)], } for step in range(cfg["steps"]) ]
def save_checkpoint(path, engine, opt, job, step, history, ledger): temporary = path.with_suffix(f".{os.getpid()}.tmp") torch.save( { "delta": engine.delta.detach().cpu(), "optimizer": opt.state_dict(), "job": job, "step": step, "history": history, "ledger": ledger, "execution_lock": digest(ART / "execution-lock.json"), }, temporary, ) temporary.replace(path)
def evaluate_node(engine, episode, selection, texts, step, output, full_test=False): result = { "step": step, "time": now(), "E": engine.evaluate(episode, views=(0, 1, 2, 3), with_kl=False), "R": engine.evaluate(selection["R"]), "V": engine.evaluate(selection["V"]), "text_dev": engine.evaluate_text(texts["dev"]), "delta_norm": float(engine.delta.norm()), "relative_delta_norm": float(engine.delta.norm() / engine.down.weight.norm()), } if full_test: result["U"] = engine.evaluate(selection["U"], views=(0, 1, 2, 3)) result["text_test"] = engine.evaluate_text(texts["test"]) write(output / f"node-{step:03d}.json", result) return result
def train_job(engine, job): check_lock() cfg = engine.cfg out = RESULTS / job["id"] out.mkdir(parents=True, exist_ok=True) if (out / "complete.json").exists(): return engine.restore() selection, texts = read(DATA / "selection.json"), read(DATA / "text.json") phase = job["phase"] records = selection["E_dev" if phase == "dev" else "E_confirm"] episode = records[job["episode"] * 4 : (job["episode"] + 1) * 4] training_enc = [r["encoded"][0] for r in episode] reference_enc = ( [r["encoded"][0] for role in ("R", "V") for r in selection[role]] + texts["train"] + texts["dev"] ) if phase == "confirm": reference_enc += [enc for r in selection["U"] for enc in r["encoded"]] + texts["test"] missing = [e for e in reference_enc if e["key"] not in engine.reference] engine.cache_reference(missing) if job["condition"] != "ordinary": engine.route = "group" if job["condition"] == "candidate" else "random" engine.route_group = job["group"] engine.route_seed = job["seed"] opt = optimizer(engine, job["lr"]) batches = schedule(cfg, job["episode"], job["seed"]) write(out / "schedule.json", batches) history, ledger, start = ( [], { "E_sequences": 0, "R_sequences": 0, "text_sequences": 0, "supervised_E_tokens": 0, "R_prediction_tokens": 0, "text_prediction_tokens": 0, "padded_training_tokens": 0, }, 0, ) checkpoint = out / "latest.pt" if checkpoint.exists(): ck = torch.load(checkpoint, map_location=engine.device, weights_only=False) assert ck["job"] == job and ck["execution_lock"] == digest(ART / "execution-lock.json") with torch.no_grad(): engine.delta.copy_(ck["delta"]) opt.load_state_dict(ck["optimizer"]) history, ledger, start = ck["history"], ck["ledger"], ck["step"] else: evaluate_node(engine, episode, selection, texts, 0, out, phase == "confirm") save_checkpoint(out / "step-000.pt", engine, opt, job, 0, history, ledger) begun = time.time() torch.cuda.reset_peak_memory_stats(engine.device) for index in range(start, cfg["steps"]): plan = batches[index] replay = [selection["R"][i]["encoded"][0] for i in plan["R"]] text = [texts["train"][i] for i in plan["text"]] opt.zero_grad(set_to_none=True) ce, _ = engine.objectives(training_enc, include_kl=False) ce.mean().backward() _, rkl = engine.objectives(replay) (job["beta"] * rkl.mean() / 2).backward() _, tkl = engine.objectives(text) (job["beta"] * tkl.mean() / 2).backward() gradient_norm = torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) if not torch.isfinite(gradient_norm): raise RuntimeError(f"Non-finite gradient in {job['id']} step {index + 1}") opt.step() history.append( { "step": index + 1, "ce": float(ce.detach().mean()), "r_kl": float(rkl.detach().mean()), "text_kl": float(tkl.detach().mean()), "gradient_norm_before_clip": float(gradient_norm), } ) ledger["E_sequences"] += len(training_enc) ledger["R_sequences"] += len(replay) ledger["text_sequences"] += len(text) ledger["supervised_E_tokens"] += sum(sum(e["loss_mask"]) for e in training_enc) ledger["R_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in replay) ledger["text_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in text) ledger["padded_training_tokens"] += sum( len(es) * max(len(e["input_ids"]) for e in es) for es in (training_enc, replay, text) ) step = index + 1 if step in cfg["nodes"]: evaluate_node(engine, episode, selection, texts, step, out, phase == "confirm") save_checkpoint(out / f"step-{step:03d}.pt", engine, opt, job, step, history, ledger) if step % 16 == 0 or step in cfg["nodes"]: save_checkpoint(checkpoint, engine, opt, job, step, history, ledger) write( out / "status.json", { "time": now(), "state": "training", "step": step, "job": job, "device": str(engine.device), "seconds_this_attempt": time.time() - begun, }, ) print(json.dumps({"job": job["id"], "step": step, "ce": history[-1]["ce"]}), flush=True) write(out / "history.json", history) write( out / "complete.json", { "time": now(), "job": job, "steps": cfg["steps"], "ledger": ledger, "schedule_sha256": digest(out / "schedule.json"), "seconds_this_attempt": time.time() - begun, "peak_gpu_bytes": torch.cuda.max_memory_allocated(engine.device), "device": str(engine.device), "trainable_parameters": engine.delta.numel(), "parent_down_hash": engine.base_hash, "forward_tokens_engine_cumulative": engine.forward_tokens, "flops_estimate": { "convention": "Approximate dense 2*N per forward token plus backward through " "downstream half and head; padding included, attention term omitted; " "reference/evaluation costs recorded separately", "value": 4 * sum(p.numel() for p in engine.model.parameters()) * ledger["padded_training_tokens"], "not_hardware_counter": True, }, }, ) engine.restore()
def train_shard(device, shard, shards): engine = PathEngine(device) for index, job in enumerate(jobs()): if index % shards == shard: train_job(engine, job)
def select_learning_rates(): cfg = read(CONFIG) summaries, chosen = [], {} for beta in cfg["betas_replay"]: options = [] for lr in cfg["learning_rates"]: records = [] for job in jobs(): if job["beta"] == beta and job["lr"] == lr: assert (RESULTS / job["id"] / "complete.json").exists() node = read(RESULTS / job["id"] / "node-128.json") base = read(RESULTS / job["id"] / "node-000.json") records.append( { "E": mean([r for r in node["E"] if r["view"] == 0], "correct"), "V_loss": mean(base["V"], "correct") - mean(node["V"], "correct"), "text_kl": mean(node["text_dev"], "kl"), } ) option = { "beta": beta, "lr": lr, **{k: mean(records, k) for k in ("E", "V_loss", "text_kl")}, } options.append(option) eligible = [r for r in options if r["V_loss"] <= 0.05] if eligible: choice = min(eligible, key=lambda r: (-r["E"], r["text_kl"], r["lr"])) else: choice = min(options, key=lambda r: (r["V_loss"], r["text_kl"], r["lr"])) chosen[str(beta)] = {**choice, "retention_condition_passed": bool(eligible)} summaries.extend(options) write( ART / "learning-rate-selection.json", {"time": now(), "node": 128, "rows": summaries, "chosen": chosen, "used_U": False}, ) return chosen
@torch.no_grad()def diagnose(device, episode_index): check_lock() cfg = read(CONFIG) chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] job = next( j for j in jobs() if j["episode"] == episode_index and j["beta"] == 1 and j["lr"] == chosen["lr"] ) engine = PathEngine(device) selection = read(DATA / "selection.json") episode = selection["E_dev"][episode_index * 4 : (episode_index + 1) * 4] records = episode + selection["R"] encs = [r["encoded"][0] for r in records] engine.cache_reference(encs) output = RESULTS / job["id"] / "diagnostics" output.mkdir(exist_ok=True) base_E = engine.evaluate(episode) zero_R = engine.evaluate(selection["R"], generate=False) for step in cfg["nodes"][1:]: if (output / f"step-{step:03d}.json").exists(): continue ck = torch.load( RESULTS / job["id"] / f"step-{step:03d}.pt", map_location=engine.device, weights_only=False, ) engine.delta.copy_(ck["delta"]) engine.route = "all" full_E = engine.evaluate(episode) full_R = engine.evaluate(selection["R"], generate=False) energies = {} for start in range(0, len(encs), 8): chunk = encs[start : start + 8] engine.capture = [] engine.objectives(chunk, include_kl=False) captured = engine.capture[0] for i, enc in enumerate(chunk): energies[enc["key"]] = captured[i, : len(enc["roles"])].tolist() engine.capture = None result = { "step": step, "episode": episode_index, "job": job, "base_E": base_E, "zero_R": zero_R, "all_E": full_E, "all_R": full_R, "groups": {}, } for group in cfg["groups"] + ["L", "A"]: engine.route, engine.route_group = "group", group group_E = engine.evaluate(episode) group_R = engine.evaluate(selection["R"], generate=False) group_result = {"E": group_E, "R": group_R, "random": []} if group in cfg["groups"]: for seed in cfg["matching"]["diagnostic_seeds"]: positions, matches = {}, {} for enc in encs: selected, info = random_positions( enc["roles"], group, enc["key"], seed, cfg["matching"]["position_bins"], cfg["matching"]["draws"], energies[enc["key"]], ) info["energy_matched"] = ( info["valid"] and info["relative_energy_error"] <= cfg["matching"]["norm_relative_tolerance"] ) matches[enc["key"]] = info positions[enc["key"]] = selected engine.route, engine.route_positions = "positions", positions group_result["random"].append( { "seed": seed, "matches": matches, "positions": positions, "E": engine.evaluate(episode), "R": engine.evaluate(selection["R"], generate=False), } ) result["groups"][group] = group_result engine.route = "all" recovered = engine.evaluate(episode, generate=False) result["restore_max_ce_error"] = max( abs(a["ce"] - b["ce"]) for a, b in zip(full_E, recovered, strict=True) ) result["position_energy"] = energies write(output / f"step-{step:03d}.json", result) print(json.dumps({"diagnostic_episode": episode_index, "step": step}), flush=True) engine.restore()
def candidate_decision(): cfg = read(CONFIG) chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] rows = [] for job in jobs(): if job["beta"] != 1 or job["lr"] != chosen["lr"]: continue d = read(RESULTS / job["id"] / "diagnostics/step-128.json") gain = mean(d["base_E"], "ce") - mean(d["all_E"], "ce") risk = mean(d["all_R"], "kl") noise = max(abs(r["kl"]) for r in d["zero_R"]) for group in cfg["groups"]: g = d["groups"][group] retained = None if gain <= 0 else (mean(d["base_E"], "ce") - mean(g["E"], "ce")) / gain reduction = None if risk <= 0 else 1 - mean(g["R"], "kl") / risk matching = [] for control in g["random"]: matched_ids = { int(key.split("-")[1]) for key, m in control["matches"].items() if m["energy_matched"] } e_fraction = sum(r["case_id"] in matched_ids for r in d["all_E"]) / len(d["all_E"]) r_fraction = sum(r["case_id"] in matched_ids for r in d["all_R"]) / len(d["all_R"]) all_r = [r for r in d["all_R"] if r["case_id"] in matched_ids] cand_r = [r for r in g["R"] if r["case_id"] in matched_ids] random_r = [r for r in control["R"] if r["case_id"] in matched_ids] difference = None if not all_r else mean(random_r, "kl") - mean(cand_r, "kl") matching.append( { "seed": control["seed"], "E_coverage": e_fraction, "R_coverage": r_fraction, "candidate_minus_random_improvement": difference, "valid": e_fraction >= cfg["matching"]["minimum_coverage"] and r_fraction >= cfg["matching"]["minimum_coverage"], } ) valid = [m for m in matching if m["valid"]] beats_random = ( bool(valid) and float(np.median([m["candidate_minus_random_improvement"] for m in valid])) > cfg["gate"]["noise_multiplier"] * noise ) passes = bool( gain > 0 and mean(d["all_E"], "correct") > mean(d["base_E"], "correct") and retained >= cfg["gate"]["learning_retained"] and mean(g["E"], "correct") >= mean(d["all_E"], "correct") and risk >= max(cfg["gate"]["kl_floor"], cfg["gate"]["noise_multiplier"] * noise) and reduction >= cfg["gate"]["kl_reduction"] and beats_random ) rows.append( { "episode": job["episode"], "group": group, "E_gain": gain, "learning_retained": retained, "R_kl": risk, "R_kl_reduction": reduction, "E_correct_all": mean(d["all_E"], "correct"), "E_correct_candidate": mean(g["E"], "correct"), "noise": noise, "matching": matching, "beats_random": beats_random, "passes": passes, } ) eligible = [ g for g in cfg["groups"] if sum(r["passes"] for r in rows if r["group"] == g) >= cfg["gate"]["units_required"] ] winner = ( min( eligible, key=lambda g: ( -float(np.mean([r["R_kl_reduction"] for r in rows if r["group"] == g])), cfg["groups"].index(g), ), ) if eligible else None ) result = { "time": now(), "rows": rows, "candidate": winner, "status": "eligible_for_confirmation" if winner else "stop_after_development", "confirmation_started": False, "selection_uses_U": False, "coverage_rule": "At least 80% of E and R must have disjoint count/bin/energy matches " "in a fixed random seed; compare candidate/random on identical matched records", } write(ART / "candidate-decision.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416"""Frozen-weight update deletion and semantic first-hop interventions.
Responses are measurements of computational dependence, not learned predictors.Truth graphs select donors before inference; query means prevent donor frequencyfrom creating additional scientific observations."""
from __future__ import annotations
import time
import numpy as npimport torchfrom torch.nn import functional as F
from .depth_step import EOS, prompt_rows, truth_path_detailsfrom .latent_scaling import model_digest
COMPONENTS = ("full", "attention", "mlp")TASKS = ("atomic",) + tuple(f"{s}_{h}" for h in (2, 3, 4) for s in ("familiar", "strict"))
@torch.no_grad()def trace(model, tokens, repeats, *, skip=None, patch=None): """Apply one occurrence deletion or one r1 replacement, with native SDPA.""" if model.training or repeats < 1: raise ValueError("Evaluation mode and positive recurrence are required") blocks = list(model.iter_blocks(repeats)) if skip is not None: scope, source = skip if scope not in ("all", "r1") or source not in range(len(blocks)): raise ValueError("Unknown skip scope/occurrence") if patch is not None and patch[0] not in ("full", "mlp"): raise ValueError("Unknown patch component") x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) cache = {name: [] for name in ("input", "full", "attention", "mlp", "output")} for index, block in enumerate(blocks): incoming = x 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) attention = a.proj( F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0, ) .transpose(1, 2) .reshape(batch, length, width) ) x = x + attention mlp = block.mlp(block.ln2(x)) if index == 0 and patch is not None and patch[0] == "mlp": mlp = mlp.clone() if patch[1].shape != mlp[:, 2].shape: raise ValueError("Replacement shape differs") mlp[:, 2] = patch[1] x = x + mlp if index == 0 and patch is not None and patch[0] == "full": x = x.clone() if patch[1].shape != x[:, 2].shape: raise ValueError("Replacement shape differs") x[:, 2] = patch[1] if skip is not None and index == skip[1]: if skip[0] == "all": x, attention, mlp = incoming, torch.zeros_like(attention), torch.zeros_like(mlp) else: x, attention, mlp = x.clone(), attention.clone(), mlp.clone() x[:, 2], attention[:, 2], mlp[:, 2] = incoming[:, 2], 0, 0 for name, value in zip(cache, (incoming, x - incoming, attention, mlp, x), strict=True): cache[name].append(value) logits = F.linear(model.ln_final(x), model.token.weight) return logits, {name: torch.stack(values) for name, values in cache.items()}
def interaction(numerator, denominator): """Ratio of query-averaged norms; an absent denominator is not zero influence.""" numerator, denominator = np.asarray(numerator), np.asarray(denominator) if numerator.shape != denominator.shape or not len(numerator): raise ValueError("Require nonempty aligned response arrays") n, b = float(numerator.mean()), float(denominator.mean()) return {"N": n, "B": b, "C": n / b if b > 1e-8 else None}
def prediction_metrics(prediction, targets): generated = prediction["generated"] logits = prediction["logits"].astype(np.float64) targets = np.asarray(targets, dtype=np.int64) maximum = logits.max(1) partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(1)) target_logits = logits[np.arange(len(targets)), targets] competitors = logits.copy() competitors[np.arange(len(targets)), targets] = -np.inf return { "answer": (generated[:, 0] == targets).astype(float), "complete": ((generated[:, 0] == targets) & (generated[:, 1] == EOS)).astype(float), "eos": (generated[:, 1] == EOS).astype(float), "nll": partition - target_logits, "margin": target_logits - competitors.max(1), }
def mean_metrics(metrics, mask=None): length = len(next(iter(metrics.values()))) mask = np.ones(length, bool) if mask is None else np.asarray(mask, dtype=bool) if mask.shape != (length,): raise ValueError("Mask must align with observations") return { "n": int(mask.sum()), "coverage": float(mask.mean()) if length else 0.0, **{k: float(v[mask].mean()) if mask.any() else None for k, v in metrics.items()}, }
def query_means(values, indices, n): counts = np.bincount(indices, minlength=n) sums = np.bincount(indices, weights=values, minlength=n) out = np.full(n, np.nan) np.divide(sums, counts, out=out, where=counts > 0) return out
def role_counts(world): counts = np.zeros((len(world["atomic"]), 4), dtype=np.int64) for hop in (2, 3, 4): _, edges = truth_path_details(world, world[f"train_{hop}"]) for position in range(hop): np.add.at(counts[:, position], edges[:, position], 1) return counts
def select_donors(low, high): """Enumerate shared bridge donors and select answer-blind changed paths.""" atoms = low["atomic"] for name in TASKS: np.testing.assert_array_equal(low[name], high[name]) id_mask = np.asarray(low["metadata"]["id_mask"], bool) np.testing.assert_array_equal(id_mask, high["metadata"]["id_mask"]) low_roles, high_roles = role_counts(low), role_counts(high) if low_roles[~id_mask].any() or high_roles[~id_mask].any(): raise ValueError("Strict fact has composition training exposure") used_first = (low_roles[:, 0] > 0) & (high_roles[:, 0] > 0) strict = ~id_mask & (low_roles.sum(1) == 0) & (high_roles.sum(1) == 0) result = {"low_roles": low_roles, "high_roles": high_roles} rows = low["strict_2"] nodes, _ = truth_path_details(low, rows) for label, eligible in (("experienced", used_first), ("strict", strict)): recipients, indices = [], [] for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): mask = eligible & (atoms[:, 1] == row[1]) & (atoms[:, 2] == path[1]) mask &= (atoms[:, 0] != row[0]) & (atoms[:, 0] != row[-1]) choices = sorted(np.flatnonzero(mask), key=lambda k: tuple(atoms[k])) recipients.extend([i] * len(choices)) indices.extend(choices) result[label + "_recipients"] = np.asarray(recipients, dtype=np.int64) result[label + "_atoms"] = np.asarray(indices, dtype=np.int64) result["common"] = (np.bincount(result["experienced_recipients"], minlength=len(rows)) > 0) & ( np.bincount(result["strict_recipients"], minlength=len(rows)) > 0 ) lookup = {(int(h), int(r)): (i, int(t)) for i, (h, r, t) in enumerate(atoms)} trained = {tuple(row[:-1]) for w in (low, high) for row in w["train_2"]} order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) for label in ("familiar", "strict"): rows = low[label + "_2"] nodes, edges = truth_path_details(low, rows) recipients, donors, targets, successors = [], [], [], [] for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): for fact in order: h, r1, bridge = map(int, atoms[fact]) successor = lookup.get((bridge, int(row[2]))) if successor is None: continue next_index, target = successor if ( r1 != row[1] or h in (row[0], row[-1], target) or bridge == path[1] or target == row[-1] or (h, r1, int(row[2])) in trained or id_mask[fact] != id_mask[edges[i, 0]] or id_mask[next_index] != id_mask[edges[i, 1]] ): continue recipients.append(i) donors.append(fact) targets.append(target) successors.append(next_index) break result[label + "_changed_recipients"] = np.asarray(recipients, dtype=np.int64) result[label + "_changed_atoms"] = np.asarray(donors, dtype=np.int64) result[label + "_changed_targets"] = np.asarray(targets, dtype=np.int64) result[label + "_changed_successors"] = np.asarray(successors, dtype=np.int64) return result
@torch.no_grad()def generate(model, rows, separator, repeats, *, skip=None, donor_atoms=None, component="full"): """Free answer and free EOS; a donor sees only the atomic question prefix.""" rows = np.asarray(rows, np.int64) if not len(rows): return { "generated": np.empty((0, 2), np.int64), "logits": np.empty((0, model.config.vocab_size), np.float32), }, None device = next(model.parameters()).device tokens = torch.as_tensor(prompt_rows(rows, separator), device=device)
def forward(inputs): patch = None if donor_atoms is not None: donor = torch.zeros_like(inputs) donor[:, :3] = torch.as_tensor( prompt_rows(donor_atoms, separator)[:, :3], device=device ) _, donor_cache = trace(model, donor, 1) field = "output" if component == "full" else "mlp" patch = (component, donor_cache[field][0, :, 2]) return trace(model, inputs, repeats, skip=skip, patch=patch)
logits, cache = forward(tokens) answer_logits = logits[:, -1] answer = answer_logits.argmax(-1) eos_logits, _ = forward(torch.cat((tokens, answer[:, None]), dim=1)) prediction = { "generated": torch.stack((answer, eos_logits[:, -1].argmax(-1)), 1).cpu().numpy(), "logits": answer_logits.cpu().numpy(), } return prediction, cache
def response_arrays(baseline, changed, source): arrays, rows = {}, [] for component in COMPONENTS: for site, position in (("all", None), ("r1", 2), ("answer", -1)): a, b = baseline[component], changed[component] n, d = (b - a).norm(dim=-1), a.norm(dim=-1) n, d = ( (n.mean(-1), d.mean(-1)) if position is None else (n[..., position], d[..., position]) ) for target in range(source + 1, len(a)): numerator, denominator = n[target].cpu().numpy(), d[target].cpu().numpy() key = f"{component}_{site}_i{source}_j{target}" arrays[key + "_N"], arrays[key + "_B"] = numerator, denominator rows.append( { "component": component, "site": site, "source": source, "target": target, **interaction(numerator, denominator), } ) return arrays, rows
@torch.no_grad()def evaluate(model, world, selection, repeats): started = time.perf_counter() if any(p.requires_grad for p in model.parameters()) or model.training: raise ValueError("All weights must be frozen in evaluation mode") before = model_digest(model) model.repeats = repeats separator = world["metadata"]["separator_token"] arrays, summaries, engineering = {}, {}, {} predictions, caches, metrics = {}, {}, {} conditions = [("baseline", None)] + [ (f"skip_{scope}_{i}", (scope, i)) for scope in ("all", "r1") for i in range(repeats) ] for task in TASKS: rows = world[task] arrays[task + "_rows"] = rows predictions[task], metrics[task] = {}, {} for name, skip in conditions: pred, cache = generate(model, rows, separator, repeats, skip=skip) m = prediction_metrics(pred, rows[:, -1]) predictions[task][name], metrics[task][name] = pred, m for field, values in {**pred, **m}.items(): arrays[f"{task}_{name}_{field}"] = values summaries[f"{task}/{name}"] = {"full_pool": mean_metrics(m)} if name == "baseline": caches[task] = cache inputs = torch.as_tensor( prompt_rows(rows, separator), device=next(model.parameters()).device ) native = model(inputs)[:, -1].cpu().numpy() if not np.array_equal(native, pred["logits"]): raise AssertionError("Traced logits differ from native forward") engineering[task + "_native_logits_exact"] = True elif task != "atomic": response, cells = response_arrays(caches[task], cache, skip[1]) arrays.update({f"{task}_{name}_{k}": v for k, v in response.items()}) summaries[f"{task}/{name}"]["responses"] = cells if name == f"skip_r1_{repeats - 1}": for field in ("generated", "logits"): np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) engineering[task + "_last_r1_no_downstream_effect"] = True del cache for task in TASKS[1:]: _, edges = truth_path_details(world, world[task]) arrays[task + "_atomic_indices"] = edges common = np.ones(len(world[task]), bool) for name, _ in conditions: common &= metrics["atomic"][name]["complete"][edges].all(1) arrays[task + "_common_atomic_mask"] = common for name, _ in conditions: cell = summaries[f"{task}/{name}"] cell["necessary_atomic_coverage"] = float( metrics["atomic"][name]["complete"][edges].all(1).mean() ) cell["common_atomic_pool"] = mean_metrics(metrics[task][name], common) # Self-prefix patches at equal physical length verify absence of later-relation information. for task in ("familiar_2", "strict_2"): rows = world[task] atoms = np.c_[rows[:, :2], np.zeros(len(rows), np.int64)] for component in ("full", "mlp"): pred, _ = generate( model, rows, separator, repeats, donor_atoms=atoms, component=component ) for field in ("generated", "logits"): np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) engineering[f"{task}_self_prefix_{component}_exact"] = True rows = world["strict_2"] _, edges = truth_path_details(world, rows) common = selection["common"] donor_atom_ok = np.ones(len(world["atomic"]), bool) for label in ("experienced", "strict"): recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] donor_atom_ok[facts] = metrics["atomic"]["baseline"]["complete"][facts].astype(bool) for component in ("full", "mlp"): if not len(recipients): continue pred, _ = generate( model, rows[recipients], separator, repeats, donor_atoms=world["atomic"][facts], component=component, ) m = prediction_metrics(pred, rows[recipients, -1]) key = f"same_{label}_{component}" for field, value in {**pred, **m}.items(): arrays[key + "_" + field] = value balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} summaries[key] = { "common_graph_pool": mean_metrics(balanced, common), "all_available": mean_metrics(balanced, np.isfinite(balanced["complete"])), } known = metrics["atomic"]["baseline"]["complete"][edges].all(1) for label in ("experienced", "strict"): recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] for recipient, fact in zip(recipients, facts, strict=True): known[recipient] &= donor_atom_ok[fact] arrays["same_common_known_mask"] = known & common summaries["same_baseline"] = { "common_graph_pool": mean_metrics(metrics["strict_2"]["baseline"], common), "common_known_pool": mean_metrics(metrics["strict_2"]["baseline"], known & common), } for label in ("experienced", "strict"): recipients = selection[label + "_recipients"] for component in ("full", "mlp"): key = f"same_{label}_{component}" if key in summaries: m = { k: arrays[key + "_" + k] for k in ("answer", "complete", "eos", "nll", "margin") } balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} summaries[key]["common_known_pool"] = mean_metrics(balanced, known & common) for label in ("familiar", "strict"): task = label + "_2" recipients = selection[label + "_changed_recipients"] facts = selection[label + "_changed_atoms"] targets = selection[label + "_changed_targets"] if not len(recipients): continue original = world[task][recipients] counterfactual = original.copy() counterfactual[:, 0] = world["atomic"][facts, 0] counterfactual[:, -1] = targets truth_path_details(world, counterfactual) native_cf, _ = generate(model, counterfactual, separator, repeats) values = { "baseline": {k: v[recipients] for k, v in predictions[task]["baseline"].items()}, "counterfactual": native_cf, } for component in ("full", "mlp"): values[component], _ = generate( model, original, separator, repeats, donor_atoms=world["atomic"][facts], component=component, ) for name, pred in values.items(): key = f"changed_{label}_{name}" m = prediction_metrics(pred, targets) for field, vector in {**pred, **m}.items(): arrays[key + "_" + field] = vector summaries[key] = mean_metrics(m) arrays.update({"selection_" + k: v for k, v in selection.items()}) if model_digest(model) != before: raise AssertionError("Intervention changed model parameters") return arrays, { "repeats": repeats, "seconds": time.perf_counter() - started, "weights_unchanged": True, "model_sha256": before, "engineering": engineering, "conditions": summaries, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""Intermediate supervision and input-compatible states in complete causal GPTs.
The intervention observes the first executed block at the first relation token.Every arm executes the same forward/backward graph. Ordinary full-token CE,auxiliary entity CE, and state geometry are recorded separately."""
from __future__ import annotations
import hashlibimport jsonimport osimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_model import LoopGPT, flopsfrom .latent_scaling import build_world, construct, model_digestfrom .storage_composition import data_digest, evaluate, file_hash, pack_sentencesfrom .storage_frontier import learning_rate
class RepresentationGPT(LoopGPT): """Unchanged GPT/Loop computation, optionally exposing a causal early state."""
def forward(self, tokens, positions=None, repeats=None, return_bridge=False): 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) bridge = 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 and return_bridge: bridge = x[:, 3] 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, bridge) if return_bridge else logits
def new_model(spec, device): # Construct through the established initializer, then replace only the type. model = construct(spec, device) model.__class__ = RepresentationGPT return model
def pack_training(world): strata = [world[k] for k in ("common_atomic", "train_composite", "anchor_atomic")] tokens, labels = ( np.concatenate(parts) for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) ) # Column 2 is the atomic answer or the composition's first-hop answer. # It never enters the composed input; it is an explicit auxiliary target. targets = np.concatenate([rows[:, 2] for rows in strata]) return (tokens, labels, targets), [len(rows) for rows in strata]
def objective(model, tokens, labels, targets, bridge_weight, alignment_weight): logits, bridge = model(tokens, return_bridge=True) text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) bridge_ce = F.cross_entropy(bridge_logits, targets) canonical = model.token(targets).detach() alignment = ( (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() ) parts = torch.stack((text_ce, bridge_ce, alignment)) return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts
class RepresentationStep(GraphStep): def __init__(self, model, optimizer, table, batch_size, spec): self.spec = spec super().__init__(model, optimizer, table, batch_size)
def eager(self): self.optimizer.zero_grad(set_to_none=False) tokens, labels, targets = (part[self.index] for part in self.table) loss, self.components = objective( self.model, tokens, labels, targets, self.spec["bridge_weight"], self.spec["alignment_weight"], ) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def run_name(spec): return f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-{spec['arm']}"
def train(spec, out, source, device): 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.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_device(device) started = time.perf_counter() world = build_world(spec) np.savez_compressed(out / "world.npz", **world) arrays, sizes = pack_training(world) model = new_model(spec, device) initial_hash = model_digest(model) write_json( out / "run.json", { "spec": spec, "source": source, "world_sha256": data_digest(world), "initial_model_sha256": initial_hash, "pid": os.getpid(), "gpu": device.index, "gpu_name": torch.cuda.get_device_name(device), "dtype": "float32", "parameters": sum(p.numel() for p in model.parameters()), "atomic_examples": sizes[0] + sizes[2], "composition_examples": sizes[1], "vocab_size": model.config.vocab_size, }, ) table = tuple(torch.as_tensor(a, device=device) for a in arrays) lr = torch.tensor(spec["lr"], device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) model.train() graph = RepresentationStep(model, optimizer, table, spec["batch_size"], spec) assert model_digest(model) == initial_hash, "CUDA capture changed initialization" streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] offsets = np.cumsum([0, *sizes[:-1]]) counts = [np.zeros(n, dtype=np.int64) for n in sizes] input_hash = hashlib.sha256() history, step, training_seconds = [], 0, 0.0 flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) # All arms also execute the auxiliary readout and normalization. flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size
def measure(): metrics, predictions = evaluate(model, world, "low", device) parts = graph.components.detach().cpu().tolist() if step else [None] * 3 row = { "step": step, "metrics": metrics, "text_ce": parts[0], "bridge_ce": parts[1], "alignment_loss": parts[2], "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "examples": step * spec["batch_size"], "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), "auxiliary_target_presentations": step * spec["batch_size"], "estimated_matmul_training_flops": step * flop_step, "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) print( json.dumps( { "run": run_name(spec), "step": step, "atomic": metrics["common_atomic"]["accuracy"], "train": metrics["train_composite"]["accuracy"], "familiar": metrics["familiar_test"]["accuracy"], "strict": metrics["strict_test"]["accuracy"], } ), flush=True, ) model.train()
measure() for end in spec["nodes"][1:]: torch.cuda.synchronize(device) began = time.perf_counter() while step < end: n = min(128, end - step) indices = [] for j, stream in enumerate(streams): drawn = stream.take(n * spec["batch_size"] // 3).reshape(n, -1) counts[j] += np.bincount(drawn.ravel(), minlength=sizes[j]) indices.append(drawn + offsets[j]) indices = np.concatenate(indices, axis=1) input_hash.update(indices.tobytes()) indices = torch.as_tensor(indices, device=device) for j in range(n): lr.fill_(learning_rate(spec, step + j + 1)) loss = graph(indices[j]) step += n torch.cuda.synchronize(device) training_seconds += time.perf_counter() - began if not np.isfinite(float(loss)): raise FloatingPointError(f"Nonfinite objective at {step}") measure() model.eval() torch.save( {"spec": spec, "model": model.state_dict(), "optimizer": optimizer.state_dict()}, out / "model.pt", ) np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) write_json( out / "complete.json", { "spec": spec, "source": source, "finished_utc": utc(), "metrics": history[-1]["metrics"], "training_seconds": training_seconds, "world_sha256": data_digest(world), "initial_model_sha256": initial_hash, "sample_stream_sha256": input_hash.hexdigest(), "model_sha256": file_hash(out / "model.pt"), }, ) write_json(out / "status.json", {"state": "complete", "step": step})
def audit(out, device): out = Path(out) # Match trainer arithmetic before comparing generated tokens and NLL. 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 = new_model(spec, device) model.load_state_dict(payload["model"]) world = build_world(spec) metrics, predictions = evaluate(model, world, "low", device) saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") max_nll_error = 0.0 for key, actual in predictions.items(): if key.endswith("nll"): max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(actual, saved[key]) write_json( out / "audit.json", {"passed": True, "metrics": metrics, "max_nll_error": max_nll_error, "allow_tf32": True}, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543"""Development comparison in an unchanged, fully trained pretrained Qwen LM.
Only training document grouping differs. All weights, native embeddings,residuals, attention, norms and distinct MLP layers are retained."""
from __future__ import annotations
import hashlibimport jsonimport mathimport reimport shutilimport timefrom collections import Counterfrom datetime import datetime, timezonefrom pathlib import Path
import numpy as npimport torchimport transformersfrom transformers import AutoModelForCausalLM, AutoTokenizer
QUESTIONS = ( ( "Who is {head}'s mentor?", "Who mentors {head}?", "Name the mentor of {head}.", "Who is the mentor of {head}?", ), ( "Which city does {bridge} live in?", "What city is {bridge}'s home?", "Where does {bridge} live?", "Name the city where {bridge} lives.", ), ( "Which city does {head}'s mentor live in?", "What city is home to {head}'s mentor?", "Where does the mentor of {head} live?", "Name the city where {head}'s mentor lives.", ),)CITIES = ( "Paris Rome London Berlin Tokyo Oslo Lima Cairo Delhi Seoul Dublin Madrid " "Vienna Boston Sydney Lisbon").split()
def read(path): return json.loads(Path(path).read_text())
def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
def sha(path): with Path(path).open("rb") as handle: return hashlib.file_digest(handle, "sha256").hexdigest()
def now(): return datetime.now(timezone.utc).isoformat()
def build_world(config): first = ( "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" ).split() last = "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() names = [f"{a} {b}" for a in first for b in last] n = config["target_triples"] + config["background_triples"] assert 2 * n <= len(names) rng = np.random.default_rng(config["world_seed"]) names = rng.permutation(names).tolist() rows = [] for split, count in ( ("target", config["target_triples"]), ("background", config["background_triples"]), ): cities = rng.permutation([CITIES[i % len(CITIES)] for i in range(count)]) for city in cities: i = len(rows) rows.append( dict(id=i, split=split, head=names[2 * i], bridge=names[2 * i + 1], city=str(city)) ) return rows
def prompt(row, hop, variant=0): return "Fictional registry.\nQuestion: " + QUESTIONS[hop][variant].format(**row) + "\nAnswer:"
def answer(row, hop): return row["bridge"] if hop == 0 else row["city"]
def encode_document(tokenizer, row, hop, variant): ids = tokenizer.encode( prompt(row, hop, variant) + " " + answer(row, hop) + ".", add_special_tokens=False ) + [tokenizer.eos_token_id] # The initial token of each atomic document has no within-document predecessor. # It remains unscored when documents are joined, preserving every target token. return dict(ids=ids, labels=[-100, *ids[1:]], triple=row["id"], hop=hop, variant=variant)
def corpus(tokenizer, world): records = {} for row in world: hops = range(3) if row["split"] == "background" else range(2) for hop in hops: for variant in range(4): records[row["id"], hop, variant] = encode_document(tokenizer, row, hop, variant) return records
def stream(config, world): rng = np.random.default_rng(config["training_seed"]) background = [r["id"] for r in world if r["split"] == "background"] result = [] for _ in range(config["steps"]): pairs = [ [int(i), int(v)] for i, v in zip( rng.choice(len(world), config["atomic_pairs_per_step"], replace=False), rng.integers(4, size=config["atomic_pairs_per_step"]), strict=True, ) ] compositions = [ [int(i), int(v)] for i, v in zip( rng.choice(background, config["background_compositions_per_step"], replace=False), rng.integers(4, size=config["background_compositions_per_step"]), strict=True, ) ] result.append(dict(pairs=pairs, compositions=compositions)) return result
def documents(records, batch, arm): docs = [] for i, v in batch["pairs"]: first, second = records[i, 0, v], records[i, 1, v] if arm == "separate": docs.extend([first, second]) elif arm == "linked": docs.append( dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) ) else: raise ValueError(arm) docs.extend(records[i, 2, v] for i, v in batch["compositions"]) return docs
def batch_tensors(docs, pad_id, device): width = max(len(d["ids"]) for d in docs) ids = torch.full((len(docs), width), pad_id, device=device, dtype=torch.long) labels = torch.full_like(ids, -100) mask = torch.zeros_like(ids) for i, doc in enumerate(docs): n = len(doc["ids"]) ids[i, :n] = torch.tensor(doc["ids"], device=device) labels[i, :n] = torch.tensor(doc["labels"], device=device) mask[i, :n] = 1 return dict(input_ids=ids, attention_mask=mask, labels=labels)
def normalize(text): return re.sub(r"\s+", " ", text.strip().rstrip(".").strip()).casefold()
def grade(text, gold): first_line = text.strip().split("\n")[0] return normalize(first_line) == normalize(gold)
def evaluation_rows(world): return [ dict(**row, hop=hop, prompt=prompt(row, hop), answer=answer(row, hop)) for row in world for hop in (range(3) if row["split"] == "target" else [2]) ]
@torch.inference_mode()def evaluate(model, tokenizer, world, config): model.eval() tokenizer.padding_side = "left" rows = evaluation_rows(world) results = [] for start in range(0, len(rows), config["eval_batch"]): chunk = rows[start : start + config["eval_batch"]] enc = tokenizer( [r["prompt"] for r in chunk], padding=True, return_tensors="pt", add_special_tokens=False, ).to(config["device"]) with torch.autocast("cuda", dtype=torch.bfloat16): generated = model.generate( **enc, do_sample=False, max_new_tokens=config["max_new_tokens"], pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, use_cache=True, )[:, enc.input_ids.shape[1] :] for row, tokens in zip(chunk, generated.cpu().tolist(), strict=True): # Drop batching padding after the first EOS; retain the actual generated EOS. if tokenizer.eos_token_id in tokens: tokens = tokens[: tokens.index(tokenizer.eos_token_id) + 1] text = tokenizer.decode(tokens, skip_special_tokens=True) results.append( dict(**row, tokens=tokens, text=text, correct=grade(text, row["answer"])) ) return results
def score(rows): result = {} for split, hop, key in ( ("target", 0, "first_hop"), ("target", 1, "second_hop"), ("target", 2, "two_hop"), ("background", 2, "background_two_hop"), ): selected = [r for r in rows if r["split"] == split and r["hop"] == hop] result[key] = sum(r["correct"] for r in selected) / len(selected) indexed = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} mastered = [ i for i, h in indexed if h == 0 and indexed[i, 0]["correct"] and indexed[i, 1]["correct"] ] result["both_atomic_coverage"] = len(mastered) / sum(h == 0 for _, h in indexed) result["two_hop_if_both_atomic"] = ( sum(indexed[i, 2]["correct"] for i in mastered) / len(mastered) if mastered else None ) return result
def prepare(config_path): config = read(config_path) art = Path(config["artifact_root"]) if (art / "lock.json").exists(): raise RuntimeError("Development lock already exists; do not overwrite it.") tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) world = build_world(config) batches = stream(config, world) records = corpus(tokenizer, world) assert all(h != 2 or world[i]["split"] == "background" for i, h, _ in records) stats = {} for arm in config["arms"]: counts = Counter() token_counts = Counter() input_tokens = supervised_tokens = padded_tokens = attention_cells = 0 for batch in batches: docs = documents(records, batch, arm) for d in docs: input_tokens += len(d["ids"]) supervised_tokens += sum(t != -100 for t in d["labels"]) counts.update(t for t in d["labels"] if t != -100) token_counts.update(d["ids"]) width = max(len(d["ids"]) for d in docs) padded_tokens += len(docs) * width attention_cells += len(docs) * width**2 stats[arm] = dict( input_tokens=input_tokens, supervised_tokens=supervised_tokens, padded_tokens=padded_tokens, attention_cells=attention_cells, target_token_counts=sorted(counts.items()), input_token_counts=sorted(token_counts.items()), ) for key in ("input_tokens", "supervised_tokens", "target_token_counts", "input_token_counts"): assert stats["separate"][key] == stats["linked"][key], key write(art / "world.json", world) write(art / "stream.json", batches) write(art / "data-audit.json", dict(status="passed", stats=stats, target_composition_labels=0)) sources = [ str(config_path), __file__, "scripts/run_small_lm_composition.py", "tests/test_small_lm_composition.py", str(art / "development-plan.md"), ] frozen = {} for source in sources: path = Path(source).resolve() relative = path.relative_to(Path.cwd()) dest = art / "source" / relative dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, dest) frozen[str(relative)] = sha(path) model_files = { str(p): sha(p) for p in Path(config["model_path"]).iterdir() if p.suffix in (".safetensors", ".json") } write( art / "lock.json", dict( status="locked_before_training", utc=now(), sources=frozen, model_files=model_files, world_sha256=sha(art / "world.json"), stream_sha256=sha(art / "stream.json"), ), ) print( json.dumps( { "status": "prepared", "stats": { a: {k: v for k, v in s.items() if not k.endswith("counts")} for a, s in stats.items() }, } ), flush=True, )
def parameter_samples(model): names = [ "model.embed_tokens.weight", "model.layers.0.self_attn.q_proj.weight", "model.layers.0.mlp.down_proj.weight", "model.layers.0.input_layernorm.weight", "model.layers.27.self_attn.o_proj.weight", "model.layers.27.mlp.down_proj.weight", ] params = dict(model.named_parameters()) return {n: params[n].detach().flatten()[:4096].clone() for n in names}
def train(config_path, arm): config = read(config_path) assert arm in config["arms"] art = Path(config["artifact_root"]) lock = read(art / "lock.json") for path, expected in lock["sources"].items(): assert sha(path) == expected, path for path, expected in lock["model_files"].items(): assert sha(path) == expected, path assert sha(art / "world.json") == lock["world_sha256"] assert sha(art / "stream.json") == lock["stream_sha256"] out = Path(config["output_root"]) / arm out.mkdir(parents=True, exist_ok=True) if (out / "status.json").exists(): raise RuntimeError("A run record already exists; preserve it and use a new output root.") write(out / "status.json", dict(status="running", arm=arm, utc=now())) begun = time.perf_counter() torch.set_num_threads(config["cpu_threads"]) torch.manual_seed(config["training_seed"]) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.cuda.set_device(config["device"]) torch.cuda.reset_peak_memory_stats() tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( config["model_path"], torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True, ).to(config["device"]) model.requires_grad_(True) assert all(p.requires_grad for p in model.parameters()) assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 assert len({id(layer.mlp) for layer in model.model.layers}) == 28 samples = parameter_samples(model) world, batches = read(art / "world.json"), read(art / "stream.json") records = corpus(tokenizer, world) optimizer = torch.optim.AdamW( model.parameters(), lr=config["learning_rate"], weight_decay=config["weight_decay"], fused=True, ) curve = [] token_count = 0 train_seconds = 0.0 initial_gradients = {} for step in range(config["steps"] + 1): if step in config["nodes"]: rows = evaluate(model, tokenizer, world, config) write(out / f"predictions-{step:05d}.json", rows) record = dict(step=step, **score(rows)) curve.append(record) write(out / "curve.json", curve) print(json.dumps(dict(arm=arm, **record)), flush=True) if step == config["steps"]: break rate = config["minimum_learning_rate"] + 0.5 * ( config["learning_rate"] - config["minimum_learning_rate"] ) * ( 1 + math.cos( math.pi * max(0, step - config["warmup_steps"]) / (config["steps"] - config["warmup_steps"]) ) ) rate *= min(1.0, (step + 1) / config["warmup_steps"]) for group in optimizer.param_groups: group["lr"] = rate model.train() docs = documents(records, batches[step], arm) inputs = batch_tensors(docs, tokenizer.pad_token_id, config["device"]) token_count += int(inputs["labels"].ne(-100).sum()) torch.cuda.synchronize() tick = time.perf_counter() optimizer.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(**inputs, use_cache=False).loss assert torch.isfinite(loss), float(loss) loss.backward() if step == 0: for name, p in model.named_parameters(): assert p.grad is not None and torch.isfinite(p.grad).all(), name if name in samples: initial_gradients[name] = float(p.grad.norm()) torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) optimizer.step() torch.cuda.synchronize() train_seconds += time.perf_counter() - tick if (step + 1) % 32 == 0: print( json.dumps( dict( arm=arm, step=step + 1, loss=float(loss), learning_rate=rate, train_seconds=train_seconds, ) ), flush=True, ) changed = { n: bool(not torch.equal(old, parameter_samples(model)[n])) for n, old in samples.items() } assert all(changed.values()), changed parameter_count = sum(p.numel() for p in model.parameters()) model.save_pretrained(out / "model", safe_serialization=True) tokenizer.save_pretrained(out / "model") final_rows = rows del optimizer, model, samples, inputs, loss torch.cuda.empty_cache() reloaded = AutoModelForCausalLM.from_pretrained( out / "model", torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True, ).to(config["device"]) reloaded_rows = evaluate(reloaded, tokenizer, world, config) assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in reloaded_rows] write( out / "reload-audit.json", dict(status="passed", predictions=len(final_rows), exact_generated_tokens=True), ) budget = read(art / "data-audit.json")["stats"][arm] assert token_count == budget["supervised_tokens"] summary = dict( status="complete", phase="development", arm=arm, utc=now(), metrics=score(final_rows), model_repo=config["model_repo"], model_revision=config["model_revision"], lock_sha256=sha(art / "lock.json"), parameter_count=parameter_count, trainable_parameters=parameter_count, sampled_parameters_changed=changed, initial_sampled_gradient_norms=initial_gradients, budget={k: v for k, v in budget.items() if not k.endswith("counts")}, updates=config["steps"], train_seconds=train_seconds, process_seconds=time.perf_counter() - begun, peak_gpu_bytes=torch.cuda.max_memory_allocated(), torch_version=torch.__version__, transformers_version=transformers.__version__, gpu=torch.cuda.get_device_name(), train_weight_dtype="float32", forward_dtype="bfloat16 autocast", tf32=False, checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, ) write(out / "summary.json", summary) write(out / "status.json", dict(status="complete", utc=now())) print(json.dumps(summary), flush=True)
def report(config_path): config = read(config_path) art = Path(config["artifact_root"]) runs, predictions = {}, {} for arm in config["arms"]: out = Path(config["output_root"]) / arm runs[arm] = read(out / "summary.json") assert runs[arm]["status"] == "complete" assert read(out / "reload-audit.json")["status"] == "passed" rows = read(out / f"predictions-{config['steps']:05d}.json") assert score(rows) == runs[arm]["metrics"] predictions[arm] = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} common = [ i for i, h in predictions["separate"] if h == 0 and all(predictions[a][i, hop]["correct"] for a in config["arms"] for hop in (0, 1)) ] conditional = { a: sum(predictions[a][i, 2]["correct"] for i in common) / len(common) if common else None for a in config["arms"] } result = dict( status="complete", phase="development_only", utc=now(), runs=runs, common_atomic_n=len(common), common_atomic_coverage=len(common) / config["target_triples"], common_atomic_two_hop=conditional, two_hop_difference=runs["linked"]["metrics"]["two_hop"] - runs["separate"]["metrics"]["two_hop"], notes=[ "One synthetic world and one training seed; no independent confirmation.", "Natural-language fictional facts; original pretrained Qwen architecture.", "Exact fact, input-token and supervised-token exposure match.", "Document grouping changes context, positions and attention work.", "Linked training co-presents the head and final city; not zero cooccurrence.", "This behavior comparison does not uniquely identify an MLP mechanism.", ], ) write(art / "summary.json", result) print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558"""Small full-Qwen development: matched rehearsal, pairing, and factual updates."""
from __future__ import annotations
import copyimport itertoolsimport jsonimport mathimport shutilimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport torchimport transformersfrom transformers import AutoModelForCausalLM, AutoTokenizer
from . import small_lm_composition as base
HELDOUT = ( "Give the name of the person mentoring {head}.", "In which city is {bridge} living?", "In which city is the person mentoring {head} living?",)
def pairing_stream(config, world): batches = base.stream(config, world) rng = np.random.default_rng(config["pairing_seed"]) for batch in batches: pairs = batch["pairs"]
def valid(order, pairs=pairs): return all( world[i]["city"] != world[pairs[k][0]]["city"] for (i, _), k in zip(pairs, order, strict=True) )
candidates = (rng.permutation(len(pairs)).tolist() for _ in range(1000)) order = next((p for p in candidates if valid(p)), None) if order is None: order = next( (list(p) for p in itertools.permutations(range(len(pairs))) if valid(p)), None ) if order is None: raise ValueError("Batch cannot match distinct cities; revise before training.") batch["second_order"] = order return batches
def training_documents(records, batch, arm, copies=1): pairs = batch["pairs"] singles = [records[i, h, v] for i, v in pairs for h in (0, 1)] docs = [] if arm == "separate": docs.extend(singles) else: order = range(len(pairs)) if arm == "linked" else batch["second_order"] if arm not in ("linked", "shuffled"): raise ValueError(arm) for (i, v), j in zip(pairs, order, strict=True): k, w = pairs[j] first, second = records[i, 0, v], records[k, 1, w] docs.append( dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) ) docs.extend(singles * copies) docs.extend(records[i, 2, v] for i, v in batch["compositions"]) return docs
def edit_design(config, world): rng = np.random.default_rng(config["edit_seed"]) ids = [] for city in base.CITIES: options = [r["id"] for r in world if r["split"] == "target" and r["city"] == city] ids.extend(int(i) for i in rng.choice(options, len(options) // 2, replace=False)) cities = rng.permutation(base.CITIES).tolist() shift = int(rng.integers(1, len(cities))) mapping = dict(zip(cities, cities[shift:] + cities[:shift], strict=True)) changed = copy.deepcopy(world) for row in changed: if row["id"] in ids: row["city"] = mapping[row["city"]] rng = np.random.default_rng(config["edit_training_seed"]) background = [r["id"] for r in world if r["split"] == "background"] batches = [] for _ in range(config["edit_steps"]): specs = [] for pool, count, hop in ( (ids, config["edited_second_per_step"], 1), (ids, config["replayed_first_per_step"], 0), (background, config["background_atomic_per_step"], None), (background, config["background_compositions_edit_per_step"], 2), ): for i in rng.choice(pool, count, replace=False): h = int(rng.integers(2)) if hop is None else hop specs.append([int(i), h, int(rng.integers(4))]) batches.append(specs) return dict(edited_ids=sorted(ids), city_mapping=mapping, world=changed, stream=batches)
def view_prompt(row, hop, view): if view == 0: return base.prompt(row, hop) return "Fictional registry.\nQuestion: " + HELDOUT[hop].format(**row) + "\nAnswer:"
def evaluation_rows(world, extras=False): return [ dict( **row, hop=hop, view=view, mode="direct", prompt=view_prompt(row, hop, view), answer=base.answer(row, hop), ) for view in ((0, 1) if extras else (0,)) for row in world if view == 0 or row["split"] == "target" for hop in range(3) ]
def autonomous_rows(world, direct): lookup = {r["id"]: r for r in world} result = [] for first in direct: if first["split"] != "target" or first["hop"] != 0: continue bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() row = lookup[first["id"]] substituted = dict(row, bridge=bridge) result.append( dict( **row, hop=2, view=first["view"], mode="autonomous", prompt=view_prompt(substituted, 1, first["view"]), answer=row["city"], generated_bridge=bridge, first_tokens=first["tokens"], first_text=first["text"], first_correct=first["correct"], ) ) return result
@torch.inference_mode()def generate(model, tokenizer, rows, config): model.eval() tokenizer.padding_side = "left" result = [] for start in range(0, len(rows), config["eval_batch"]): chunk = rows[start : start + config["eval_batch"]] x = tokenizer( [r["prompt"] for r in chunk], padding=True, return_tensors="pt", add_special_tokens=False, ).to(config["device"]) with torch.autocast("cuda", dtype=torch.bfloat16): tokens = model.generate( **x, do_sample=False, max_new_tokens=config["max_new_tokens"], pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, use_cache=True, )[:, x.input_ids.shape[1] :] for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): if tokenizer.eos_token_id in tok: tok = tok[: tok.index(tokenizer.eos_token_id) + 1] text = tokenizer.decode(tok, skip_special_tokens=True) result.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) return result
def evaluate(model, tokenizer, world, config, extras=False): direct = generate(model, tokenizer, evaluation_rows(world, extras), config) if not extras: return direct return direct + generate(model, tokenizer, autonomous_rows(world, direct), config)
def mean_correct(rows): return sum(r["correct"] for r in rows) / len(rows) if rows else None
def metrics(rows, old_world, edit): primary = [r for r in rows if r["view"] == 0 and r["mode"] == "direct"] result = base.score(primary) result["background_atomic"] = mean_correct( [r for r in primary if r["split"] == "background" and r["hop"] < 2] ) edited = set(edit["edited_ids"]) old = {r["id"]: r for r in old_world} for view in (0, 1): subset = [r for r in rows if r["view"] == view] if not subset: continue for pool, keep in (("E", True), ("U", False)): target = [r for r in subset if r["split"] == "target" and (r["id"] in edited) == keep] for hop, name in ((0, "first"), (1, "second"), (2, "two")): cell = [r for r in target if r["hop"] == hop and r["mode"] == "direct"] result[f"v{view}_{pool}_{name}"] = mean_correct(cell) if hop == 2 and cell: result[f"v{view}_{pool}_old_two"] = sum( base.grade(r["text"], old[r["id"]]["city"]) for r in cell ) / len(cell) result[f"v{view}_{pool}_autonomous"] = mean_correct( [r for r in target if r["mode"] == "autonomous"] ) if view == 1: for hop, name in ((0, "first"), (1, "second"), (2, "two")): result[f"heldout_{name}"] = mean_correct( [r for r in subset if r["mode"] == "direct" and r["hop"] == hop] ) return result
def document_budget(docs): width = max(len(d["ids"]) for d in docs) return dict( input_tokens=sum(len(d["ids"]) for d in docs), supervised_tokens=sum(sum(t != -100 for t in d["labels"]) for d in docs), padded_tokens=len(docs) * width, attention_cells=len(docs) * width**2, )
def prepare(config_path): config = base.read(config_path) art = Path(config["artifact_root"]) if (art / "lock.json").exists(): raise RuntimeError("Preserve existing lock.") tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) world = base.build_world(config) batches = pairing_stream(config, world) edit = edit_design(config, world) records = base.corpus(tokenizer, world) stats = {arm: Counter() for arm in config["arms"]} for batch in batches: signatures = [] for arm in config["arms"]: docs = training_documents(records, batch, arm, config["standalone_rehearsal_copies"]) stats[arm].update(document_budget(docs)) signatures.append( ( Counter(t for d in docs for t in d["ids"]), Counter(t for d in docs for t in d["labels"] if t != -100), ) ) assert all(s == signatures[0] for s in signatures) changed = base.corpus(tokenizer, edit["world"]) edit_stats = {branch: Counter() for branch in ("update", "replay")} for specs in edit["stream"]: for branch, rec in (("update", changed), ("replay", records)): docs = [rec[tuple(s)] for s in specs] edit_stats[branch].update(document_budget(docs)) assert [len(changed[tuple(s)]["ids"]) for s in specs] == [ len(records[tuple(s)]["ids"]) for s in specs ] assert edit_stats["update"] == edit_stats["replay"] base.write(art / "world.json", world) base.write(art / "stream.json", batches) base.write(art / "edit-design.json", edit) base.write( art / "data-audit.json", dict( status="passed", training=stats, editing=edit_stats, paired_batch_checks=len(batches), equal_edit_length_checks=len(edit["stream"]), target_composition_labels=0, edit_target_composition_labels=0, ), ) sources = [ str(config_path), str(Path(__file__).relative_to(Path.cwd())) if Path(__file__).is_absolute() else __file__, "src/llm_memory_editability/small_lm_composition.py", "scripts/run_small_lm_followup.py", "tests/test_small_lm_followup.py", str(art / "development-plan.md"), ] hashes = {} for source in sources: relative = Path(source).resolve().relative_to(Path.cwd()) dest = art / "source" / relative dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(relative, dest) hashes[str(relative)] = base.sha(relative) model_files = { str(p): base.sha(p) for p in Path(config["model_path"]).iterdir() if p.suffix in (".safetensors", ".json") } base.write( art / "lock.json", dict( status="locked_before_training", utc=base.now(), sources=hashes, model_files=model_files, data_files={ str(art / f): base.sha(art / f) for f in ("world.json", "stream.json", "edit-design.json", "data-audit.json") }, ), ) print(json.dumps(dict(status="prepared", training=stats, editing=edit_stats)), flush=True)
def check_lock(config): art = Path(config["artifact_root"]) lock = base.read(art / "lock.json") for group in ("sources", "model_files", "data_files"): for path, digest in lock[group].items(): assert base.sha(path) == digest, path
def learning_rate(step, steps, lr, minimum, warmup): decay = 0.5 * (1 + math.cos(math.pi * max(0, step - warmup) / (steps - warmup))) return (minimum + (lr - minimum) * decay) * min(1.0, (step + 1) / warmup)
def run(config_path, arm, branch=None): config = base.read(config_path) check_lock(config) assert arm in config["arms"] and branch in (None, "update", "replay") art = Path(config["artifact_root"]) root = Path(config["output_root"]) out = root / ("training" if branch is None else "editing") / arm if branch: out = out / branch if (out / "status.json").exists(): raise RuntimeError(f"Preserve existing run: {out}") old_world = base.read(art / "world.json") edit = base.read(art / "edit-design.json") # Both update and replay are scored against the SAME edited world. world = edit["world"] if branch else old_world source = Path(config["model_path"]) if branch is None else root / "training" / arm / "model" if branch: parent = base.read(root / "training" / arm / "summary.json") for path, digest in parent["checkpoint_files"].items(): assert base.sha(path) == digest steps = config["edit_steps"] if branch else config["steps"] nodes = config["edit_nodes"] if branch else config["nodes"] seed = config["edit_training_seed"] if branch else config["training_seed"] prefix = "edit_" if branch else "" batches = edit["stream"] if branch else base.read(art / "stream.json") base.write(out / "status.json", dict(status="running", utc=base.now(), arm=arm, branch=branch)) started = time.perf_counter() torch.set_num_threads(config["cpu_threads"]) torch.manual_seed(seed) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.cuda.set_device(config["device"]) torch.cuda.reset_peak_memory_stats() tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) tokenizer.pad_token = tokenizer.eos_token
def load_model(path): return AutoModelForCausalLM.from_pretrained( path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True ).to(config["device"])
model = load_model(source) model.requires_grad_(True) assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 assert len({id(layer.mlp) for layer in model.model.layers}) == 28 samples = base.parameter_samples(model) parameter_count = sum(p.numel() for p in model.parameters()) records = base.corpus(tokenizer, edit["world"] if branch == "update" else old_world) optimizer = torch.optim.AdamW( model.parameters(), lr=config[prefix + "learning_rate"], weight_decay=config["weight_decay"], fused=True, ) curve, budget = [], Counter() train_seconds = 0.0 for step in range(steps + 1): if step in nodes: rows = evaluate(model, tokenizer, world, config, extras=step == steps) base.write(out / f"predictions-{step:05d}.json", rows) record = dict(step=step, **metrics(rows, old_world, edit)) curve.append(record) base.write(out / "curve.json", curve) print(json.dumps(dict(arm=arm, branch=branch, **record)), flush=True) if step == steps: break rate = learning_rate( step, steps, config[prefix + "learning_rate"], config[prefix + "minimum_learning_rate"], config[prefix + "warmup_steps"], ) for group in optimizer.param_groups: group["lr"] = rate docs = ( [records[tuple(s)] for s in batches[step]] if branch else training_documents( records, batches[step], arm, config["standalone_rehearsal_copies"] ) ) budget.update(document_budget(docs)) inputs = base.batch_tensors(docs, tokenizer.pad_token_id, config["device"]) model.train() torch.cuda.synchronize() tick = time.perf_counter() optimizer.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(**inputs, use_cache=False).loss assert torch.isfinite(loss) loss.backward() if step == 0: assert all( p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters() ) torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) optimizer.step() torch.cuda.synchronize() train_seconds += time.perf_counter() - tick if (step + 1) % 64 == 0: print( json.dumps( dict( arm=arm, branch=branch, step=step + 1, loss=float(loss.detach()), train_seconds=train_seconds, ) ), flush=True, ) changed = { n: not torch.equal(before, base.parameter_samples(model)[n]) for n, before in samples.items() } assert all(changed.values()) architecture = model.config.to_dict() model.save_pretrained(out / "model", safe_serialization=True) tokenizer.save_pretrained(out / "model") final_rows = rows del optimizer, model, samples, inputs, loss torch.cuda.empty_cache() reloaded = load_model(out / "model") again = evaluate(reloaded, tokenizer, world, config, extras=True) assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] base.write( out / "reload-audit.json", dict( status="passed", predictions=len(again), exact_generated_tokens=True, exact_autonomous_prompts=True, ), ) expected = base.read(art / "data-audit.json") assert budget == expected["editing" if branch else "training"][branch or arm] # Dense matrix estimate: 3x forward for training; all vocab logits are evaluated. d, layers, intermediate = 1024, 28, architecture["intermediate_size"] kv = architecture["num_key_value_heads"] * architecture["head_dim"] query_width = architecture["num_attention_heads"] * architecture["head_dim"] attention_projections = 2 * d * query_width + 2 * d * kv per_token = layers * (attention_projections + 3 * d * intermediate) per_token += d * architecture["vocab_size"] flops = ( 6 * per_token * budget["padded_tokens"] + 12 * layers * (architecture["num_attention_heads"] * architecture["head_dim"]) * budget["attention_cells"] ) summary = dict( status="complete", phase="development_only", arm=arm, branch=branch, utc=base.now(), metrics=metrics(final_rows, old_world, edit), updates=steps, parameter_count=parameter_count, trainable_parameters=parameter_count, initial_all_gradients_finite=True, sampled_parameters_changed=changed, source_checkpoint=str(source), fresh_optimizer=True, budget=dict(budget), estimated_training_matrix_flops=flops, train_seconds=train_seconds, process_seconds=time.perf_counter() - started, peak_gpu_bytes=torch.cuda.max_memory_allocated(), torch_version=torch.__version__, transformers_version=transformers.__version__, gpu=torch.cuda.get_device_name(), tf32=False, lock_sha256=base.sha(art / "lock.json"), checkpoint_files={str(p): base.sha(p) for p in (out / "model").glob("*.safetensors")}, ) base.write(out / "summary.json", summary) base.write(out / "status.json", dict(status="complete", utc=base.now())) print(json.dumps(summary), flush=True)
def report(config_path): config = base.read(config_path) check_lock(config) art, root = Path(config["artifact_root"]), Path(config["output_root"]) world, edit = base.read(art / "world.json"), base.read(art / "edit-design.json") runs = {} checks = 0 for arm in config["arms"]: for branch in (None, "update", "replay"): out = root / ("editing" if branch else "training") / arm if branch: out /= branch key = f"{arm}/{branch or 'training'}" summary = base.read(out / "summary.json") assert summary["status"] == "complete" assert base.read(out / "reload-audit.json")["status"] == "passed" for node in base.read(out / "curve.json"): rows = base.read(out / f"predictions-{node['step']:05d}.json") assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) assert dict(step=node["step"], **metrics(rows, world, edit)) == node checks += len(rows) assert metrics(rows, world, edit) == summary["metrics"] runs[key] = summary result = dict( status="complete", phase="single_world_development", utc=base.now(), runs=runs, node_prediction_checks=checks, total_train_seconds=sum(r["train_seconds"] for r in runs.values()), total_process_seconds=sum(r["process_seconds"] for r in runs.values()), total_updates=sum(r["updates"] for r in runs.values()), total_input_tokens=sum(r["budget"]["input_tokens"] for r in runs.values()), total_supervised_tokens=sum(r["budget"]["supervised_tokens"] for r in runs.values()), estimated_training_matrix_flops=sum( r["estimated_training_matrix_flops"] for r in runs.values() ), lock_sha256=base.sha(art / "lock.json"), ) base.write(art / "summary.json", result) print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424"""Fact-load experiments in unmodified GPT-2 blocks and depth-shared GPT-2 blocks.
Template-language data are controlled; the architecture is an ordinary causal LM.No embeddings/projections are frozen, no intermediate answers are supplied, andall non-padding next tokens contribute to the training loss."""
from __future__ import annotations
import hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfigfrom .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_jsonfrom .grok_loop_model import LoopGPT, flopsfrom .text_pretrain import WORDS, atomic_sentence, composite_sentence
SOURCE_FILES = [ "src/llm_memory_editability/storage_composition.py", "src/llm_memory_editability/bios_model.py", "src/llm_memory_editability/grok_depth.py", "src/llm_memory_editability/grok_loop_model.py", "src/llm_memory_editability/text_pretrain.py", "scripts/run_storage_composition.py", "tests/test_storage_composition.py",]ARCHITECTURES = { "standard1": (1, 1), "standard2": (2, 1), "standard3": (3, 1), "loop1x2": (1, 2), "loop1x3": (1, 3),}
def file_hash(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def build_world(spec): """Keep the target subgraph, vocabulary and candidates fixed across loads.
Matched low load repeats anchor atomics outside every evaluated chain. High load teaches distinct distractor atomics. The original development setting repeated familiar atomics; its results are retained separately. """ rng = np.random.default_rng(spec["world"]) hn, bn, tn = (spec[k] for k in ("heads_n", "bridges_n", "tails_n")) familiar, strict = spec["familiar_n"], spec["strict_n"] core = familiar + strict if not (0 < familiar < core <= min(hn, bn)): raise ValueError("Invalid disjoint familiar/strict subgraph sizes") heads = np.arange(len(WORDS), len(WORDS) + hn) bridges = np.arange(heads[-1] + 1, heads[-1] + 1 + bn) tails = np.arange(bridges[-1] + 1, bridges[-1] + 1 + tn) first = [] for index, head in enumerate(heads): candidates = ( bridges[:familiar] if index < familiar else bridges[familiar:core] if index < core else bridges ) first.extend((head, r, rng.choice(candidates)) for r in range(13, 17)) first = np.asarray(first, dtype=np.int64) second = np.asarray( [(b, r, rng.choice(tails)) for b in bridges for r in range(17, 21)], dtype=np.int64 ) lookup = {(int(h), int(r)): int(t) for h, r, t in second} paths = np.asarray( [ (h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first[: core * 4] for r2 in range(17, 21) ], dtype=np.int64, ) familiar_paths = paths[paths[:, 0] < heads[familiar]] # Hold out entire (head, terminal) pairs, including alternate relation paths. reserved = rng.random((familiar, tn)) < spec["holdout_fraction"] held = reserved[familiar_paths[:, 0] - heads[0], familiar_paths[:, 4] - tails[0]] world = { "common_atomic": np.concatenate([first[: core * 4], second[: core * 4]]), "background_atomic": np.concatenate([first[: familiar * 4], second[: familiar * 4]]), "extra_atomic": np.concatenate([first[core * 4 :], second[core * 4 :]]), "train_composite": familiar_paths[~held], "familiar_test": familiar_paths[held], "strict_test": paths[paths[:, 0] >= heads[familiar]], } if spec.get("low_extra") == "anchors": anchors = spec["anchor_n"] if not 0 < anchors <= min(hn, bn) - core: raise ValueError("Anchor entities must be outside the common subgraph") world["anchor_atomic"] = np.concatenate( [first[core * 4 : (core + anchors) * 4], second[core * 4 : (core + anchors) * 4]] ) if any(not len(rows) for rows in world.values()): raise ValueError("Empty stratum: do not silently reroll a world") atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) audit_world(world) assert len(atoms) == 4 * (hn + bn) return world
def audit_world(world): atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} assert len(lookup) == len(atoms) for name in ("train_composite", "familiar_test", "strict_test"): for h, r1, b, r2, t in world[name]: assert lookup[int(h), int(r1)] == b assert lookup[int(b), int(r2)] == t train_pairs = {tuple(r[[0, 4]]) for r in world["train_composite"]} assert not train_pairs & {tuple(r[[0, 4]]) for r in world["familiar_test"]} train_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["train_composite"]} | { (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["train_composite"] } strict_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["strict_test"]} | { (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["strict_test"] } assert not strict_facts & train_facts assert not strict_facts & set(map(tuple, world["extra_atomic"])) if "anchor_atomic" in world: assert not set(map(tuple, world["anchor_atomic"])) & set(map(tuple, world["common_atomic"])) assert set(map(tuple, world["anchor_atomic"])) <= set(map(tuple, world["extra_atomic"]))
def pack_sentences(rows): render = atomic_sentence if rows.shape[1] == 3 else composite_sentence x = np.zeros((len(rows), 9), dtype=np.int64) labels = np.full_like(x, -100) for index, row in enumerate(rows): sentence = render(row) x[index, : len(sentence) - 1] = sentence[:-1] labels[index, : len(sentence) - 1] = sentence[1:] return x, labels
class FullTokenStep(GraphStep): def eager(self): self.optimizer.zero_grad(set_to_none=True) tokens, labels = (part[self.index] for part in self.table) logits = self.model(tokens) loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def construct(spec, device): layers, repeats = ARCHITECTURES[spec["architecture"]] config = ModelConfig( vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], width=spec["width"], layers=layers, heads=spec["heads"], context=16, ) torch.manual_seed(spec["initialization"]) if repeats == 1: model = SmallGPT(config, dropout=spec["dropout"]) else: # Same unique-block initialization as standard1, without zeroing residuals. model = LoopGPT(config, repeats, spec["dropout"], initialization="legacy_unique") return model.to(device)
@torch.no_grad()def generate_rows(model, rows, device, repeats=None, batch_size=512): """Greedy answer, then '.', then EOS; feed back every generated token.""" model.eval() if rows.shape[1] == 3: prompts = np.asarray([atomic_sentence(r)[:5] for r in rows]) else: prompts = np.asarray([composite_sentence(r)[:7] for r in rows]) predictions, nlls = [], [] kwargs = {"repeats": repeats} if isinstance(model, LoopGPT) else {} for start in range(0, len(rows), batch_size): tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) generated = [] for i in range(3): logits = model(tokens, **kwargs)[:, -1] if i == 0: nlls.append(F.cross_entropy(logits, target, reduction="none").cpu().numpy()) next_token = logits.argmax(-1) generated.append(next_token.cpu().numpy()) tokens = torch.cat([tokens, next_token[:, None]], dim=1) predictions.append(np.stack(generated, axis=1)) pred, nll = np.concatenate(predictions), np.concatenate(nlls) answer_ok = pred[:, 0] == rows[:, -1] full_ok = answer_ok & (pred[:, 1] == 5) & (pred[:, 2] == 1) metrics = { "n": len(rows), "answer_accuracy": float(answer_ok.mean()), "accuracy": float(full_ok.mean()), "answer_nll": float(nll.mean()), } return metrics, {"generated": pred, "correct": full_ok, "answer_nll": nll}
def evaluate(model, world, load, device, repeats=None): metrics, predictions = {}, {} names = ["common_atomic", "train_composite", "familiar_test", "strict_test"] if "anchor_atomic" in world: names.append("anchor_atomic") if load == "high": names.append("extra_atomic") for name in names: metrics[name], pred = generate_rows(model, world[name], device, repeats) predictions.update({name + "_" + k: v for k, v in pred.items()}) for name in ("familiar_test", "strict_test"): rows = world[name] first = rows[:, [0, 1, 2]] second = rows[:, [2, 3, 4]] _m, p1 = generate_rows(model, first, device, repeats) _m, p2 = generate_rows(model, second, device, repeats) covered = p1["correct"] & p2["correct"] generated_second = second.copy() generated_second[:, 0] = p1["generated"][:, 0] _m, autonomous = generate_rows(model, generated_second, device, repeats) calls_ok = ( (p1["generated"][:, 1] == 5) & (p1["generated"][:, 2] == 1) & autonomous["correct"] ) direct = predictions[name + "_correct"] metrics[name].update( { "atomic_correct_coverage": float(covered.mean()), "conditional_accuracy": float(direct[covered].mean()) if covered.any() else None, "autonomous_two_calls": float(calls_ok.mean()), } ) predictions.update({name + "_coverage": covered, name + "_two_calls": calls_ok}) model.train() return metrics, predictions
def data_digest(world): digest = hashlib.sha256() for key, value in sorted(world.items()): digest.update(key.encode()) digest.update(str(value.shape).encode()) digest.update(value.tobytes()) return digest.hexdigest()
def run(spec, out, device="cuda:2"): out = Path(out) if (out / "complete.json").exists(): raise FileExistsError(f"Completed run exists: {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 device = torch.device(device) torch.cuda.set_device(device) world = build_world(spec) np.savez_compressed(out / "world.npz", **world) source = {path: file_hash(path) for path in SOURCE_FILES} write_json( out / "spec.json", {"spec": spec, "source": source, "data_sha256": data_digest(world)} ) model = construct(spec, device) lr = torch.tensor(spec["lr"], device=device) opt = make_optimizer(model, lr, spec["weight_decay"]) low_extra = world["anchor_atomic"] if "anchor_atomic" in world else world["background_atomic"] extra = world["extra_atomic"] if spec["load"] == "high" else low_extra strata = [world["common_atomic"], world["train_composite"], extra] packed = [pack_sentences(rows) for rows in strata] table = tuple( torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) ) sizes = [len(rows) for rows in strata] 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] batch = spec["batch_size"] if batch % 3: raise ValueError("Batch must divide into three equal exposure strata") graph = FullTokenStep(model, opt, table, batch) history, training_seconds = [], 0.0 layers, repeats = ARCHITECTURES[spec["architecture"]] parameters = sum(p.numel() for p in model.parameters()) flop_step = flops(model.config, repeats, batch, 9, output_positions=9) start = 0
def measure(step, loss=None): metrics, predictions = evaluate(model, world, spec["load"], device) row = { "step": step, "metrics": metrics, "loss": loss, "training_seconds": training_seconds, "estimated_training_flops": step * flop_step, } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) state = { "spec": spec, "step": step, "model": model.state_dict(), "optimizer": opt.state_dict(), "streams": [s.state_dict() for s in streams], "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), "counts": counts, "source": source, "data_sha256": data_digest(world), } torch.save(state, out / "latest.tmp.pt") (out / "latest.tmp.pt").replace(out / "latest.pt") write_json( out / "status.json", { "step": step, "budget": spec["steps"], "atomic": metrics["common_atomic"]["accuracy"], "familiar": metrics["familiar_test"]["accuracy"], "strict": metrics["strict_test"]["accuracy"], }, ) print(json.dumps({"run": str(out), "step": step, "metrics": metrics}), flush=True) return row
measure(0) for end in spec["nodes"]: if end == 0: continue torch.cuda.synchronize() t0 = time.perf_counter() while start < end: n = min(128, end - start) indices = [] for i, stream in enumerate(streams): drawn = stream.take(n * batch // 3).reshape(n, batch // 3) counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) indices.append(drawn + offsets[i]) indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) for j in range(n): lr.fill_(spec["lr"] * min(1.0, (start + j + 1) / spec["warmup"])) last_loss = graph(indices[j]) start += n torch.cuda.synchronize() training_seconds += time.perf_counter() - t0 loss = float(last_loss) if not np.isfinite(loss): raise FloatingPointError(f"Nonfinite loss at {end}") endpoint = measure(end, loss) assert start == spec["steps"] # Prespecified test-time repeat sweep; these weights never change. repeat_metrics = {} if isinstance(model, LoopGPT): for count in spec["test_repeats"]: metrics, predictions = evaluate(model, world, spec["load"], device, count) repeat_metrics[str(count)] = metrics np.savez_compressed(out / f"repeat-{count:02d}.npz", **predictions) np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) write_json( out / "complete.json", { "spec": spec, "finished_utc": utc(), "parameters": parameters, "unique_blocks": layers, "executed_blocks": layers * repeats, "independent_facts": len(world["common_atomic"]) + (len(extra) if spec["load"] == "high" or "anchor_atomic" in world else 0), "training_seconds": training_seconds, "endpoint": endpoint, "repeat_metrics": repeat_metrics, "examples": start * batch, "effective_input_tokens": start * batch * 23 // 3, "supervised_tokens": start * batch * 23 // 3, "padded_input_tokens": start * batch * 9, "source": source, "data_sha256": data_digest(world), "environment": {"torch": torch.__version__, "gpu": torch.cuda.get_device_name(device)}, }, ) return endpoint
def audit_run(out, device="cuda:2"): """Independently reload the final checkpoint and regenerate all endpoint tokens.""" torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True out = Path(out) complete = json.loads((out / "complete.json").read_text()) saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) assert saved["step"] == complete["spec"]["steps"] world = build_world(saved["spec"]) assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] model = construct(saved["spec"], device) model.load_state_dict(saved["model"]) metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) expected = np.load(out / f"predictions-{saved['step']:06d}.npz") for key, value in predictions.items(): # Tiny batching/platform differences can affect NLL, never generated tokens. np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) assert metrics == complete["endpoint"]["metrics"] exposures = np.load(out / "exposures.npz") for i in range(3): np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 assert np.ptp(exposures[f"stratum{i}"]) <= 1 result = { "passed": True, "step": saved["step"], "prediction_arrays": len(predictions), "utc": utc(), } write_json(out / "audit.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Stable training and nested fact loads in ordinary GPT/Loop architectures.
The historical storage_composition implementation is reused without changing itsfrozen sources, truth, tokenizer, architecture or full-generation score."""
from __future__ import annotations
import jsonimport mathimport timefrom pathlib import Path
import numpy as npimport torch
from .grok_depth import EpochStream, make_optimizer, utc, write_jsonfrom .grok_loop_model import LoopGPT, flopsfrom .storage_composition import ( ARCHITECTURES, FullTokenStep, construct, data_digest, evaluate, file_hash, pack_sentences,)from .storage_composition import ( SOURCE_FILES as HISTORICAL_SOURCE_FILES,)from .storage_composition import ( build_world as historical_world,)
SOURCE_FILES = [ *HISTORICAL_SOURCE_FILES, "src/llm_memory_editability/storage_frontier.py", "scripts/run_storage_frontier.py", "tests/test_storage_frontier.py",]
def learning_rate(spec, step): """One-based update; paired schedules share the exact same warmup.""" if not 1 <= step <= spec["steps"]: raise ValueError("Step must be within the training budget") warmup = spec["warmup"] if warmup and step <= warmup: return spec["lr"] * step / warmup if spec["schedule"] == "constant": return spec["lr"] if spec["schedule"] != "cosine": raise ValueError("Unknown learning-rate schedule") fraction = (step - warmup) / (spec["steps"] - warmup) floor = spec["min_lr_ratio"] return spec["lr"] * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2)
def build_world(spec): world = historical_world(spec) if "extra_count" in spec: # A world-specific, fixed permutation defines nested distractor fact sets. # Common facts and every combination example remain bit-identical. count = spec["extra_count"] if not 0 < count <= len(world["extra_atomic"]): raise ValueError("Extra fact count exceeds the fixed master graph") rng = np.random.default_rng(spec["world"] + 900000) order = rng.permutation(len(world["extra_atomic"])) world["extra_atomic"] = world["extra_atomic"][order[:count]] return world
def strata_for(spec, world): extra = world["extra_atomic"] if spec["load"] == "high" else world["anchor_atomic"] return [world["common_atomic"], world["train_composite"], extra]
def run_name(spec): load = spec["load"] if "extra_count" in spec: load = f"f{spec['extra_count'] + 8 * (spec['familiar_n'] + spec['strict_n'])}" return ( f"w{spec['world']}-i{spec['initialization']}-{spec['architecture']}" f"-d{spec['width']}-{load}-{spec['schedule']}-s{spec['steps']}" )
def train(spec, out, source, device="cuda:0"): out = Path(out) out.mkdir(parents=True, exist_ok=True) if (out / "latest.pt").exists() or (out / "complete.json").exists(): raise FileExistsError(f"Do not overwrite an existing training attempt: {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) world = build_world(spec) np.savez_compressed(out / "world.npz", **world) digest = data_digest(world) write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) model = construct(spec, device) initial_sha = file_hash(out / "spec.json") lr = torch.tensor(spec["lr"], device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) strata = strata_for(spec, world) table = tuple( torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) ) sizes = [len(rows) for rows in strata] 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] batch = spec["batch_size"] if batch % 3: raise ValueError("Batch must divide into three equal streams") graph = FullTokenStep(model, optimizer, table, batch) layers, repeats = ARCHITECTURES[spec["architecture"]] flop_step = flops(model.config, repeats, batch, 9, output_positions=9) history, training_seconds, start = [], 0.0, 0
def measure(step, loss=None): metrics, predictions = evaluate(model, world, spec["load"], device) row = { "step": step, "lr": learning_rate(spec, step) if step else 0, "metrics": metrics, "loss": loss, "training_seconds": training_seconds, "estimated_training_flops": step * flop_step, } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) state = { "spec": spec, "step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "streams": [stream.state_dict() for stream 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") write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) print(json.dumps({"run": run_name(spec), "step": step, "metrics": metrics}), flush=True) return row
measure(0) for end in spec["nodes"]: if not end: continue torch.cuda.synchronize() started = time.perf_counter() while start < end: n = min(128, end - start) indices = [] for i, stream in enumerate(streams): drawn = stream.take(n * batch // 3).reshape(n, batch // 3) counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) indices.append(drawn + offsets[i]) indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) for j in range(n): lr.fill_(learning_rate(spec, start + j + 1)) last_loss = graph(indices[j]) start += n torch.cuda.synchronize() training_seconds += time.perf_counter() - started loss = float(last_loss) if not np.isfinite(loss): raise FloatingPointError(f"Nonfinite training loss at {end}") endpoint = measure(end, loss) assert start == spec["steps"] repeat_metrics = {} if isinstance(model, LoopGPT): for repeat in spec["test_repeats"]: metrics, predictions = evaluate(model, world, spec["load"], device, repeat) repeat_metrics[str(repeat)] = metrics np.savez_compressed(out / f"repeat-{repeat:02d}.npz", **predictions) np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) result = { "spec": spec, "finished_utc": utc(), "parameters": sum(p.numel() for p in model.parameters()), "unique_blocks": layers, "executed_blocks": layers * repeats, "independent_facts": len(strata[0]) + len(strata[2]), "training_seconds": training_seconds, "endpoint": endpoint, "repeat_metrics": repeat_metrics, "source": source, "data_sha256": digest, "spec_sha256": initial_sha, "checkpoint_sha256": file_hash(out / "latest.pt"), "supervised_tokens": start * batch * 23 // 3, "padded_input_tokens": start * batch * 9, "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 audit(out, device="cuda:0"): """Independent-process reload: tokens exact, floating NLL tolerance recorded.""" out = Path(out) torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_device(torch.device(device)) complete = json.loads((out / "complete.json").read_text()) saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) assert saved["step"] == complete["spec"]["steps"] assert file_hash(out / "latest.pt") == complete["checkpoint_sha256"] world = build_world(saved["spec"]) assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] model = construct(saved["spec"], device) model.load_state_dict(saved["model"]) metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) expected = np.load(out / f"predictions-{saved['step']:06d}.npz") max_nll_difference = 0.0 for key, value in predictions.items(): if key.endswith("answer_nll"): max_nll_difference = max(max_nll_difference, float(np.abs(value - expected[key]).max())) np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(value, expected[key]) for task, values in metrics.items(): for key, value in values.items(): reference = complete["endpoint"]["metrics"][task][key] if key == "answer_nll": np.testing.assert_allclose(value, reference, rtol=1e-5, atol=1e-5) else: assert value == reference exposures = np.load(out / "exposures.npz") for i in range(3): np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 assert np.ptp(exposures[f"stratum{i}"]) <= 1 result = { "passed": True, "step": saved["step"], "prediction_arrays": len(predictions), "max_nll_difference": max_nll_difference, "nll_rtol": 1e-5, "nll_atol": 1e-5, "tokens_exact": True, "utc": utc(), } write_json(out / "audit.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Factorial loss-source interventions on an unchanged text-pretraining stream."""
import hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import EpochStream, GraphStep, make_optimizer, write_jsonfrom .grok_loop_model import flopsfrom .text_pretrain import construct, evaluate, sha
ARMS = {"AB": (1, 1), "A": (1, 0), "B": (0, 1), "N": (0, 0)}SPLITS = ("atomic", "background_train", "background_test", "target_train", "target_test")
def loss_sources(labels, bounds): """0=atomic text, 1=background composition, 2=neutral text, -1=ignored.""" result = np.full(labels.shape, -1, dtype=np.int64) result[: bounds[1]] = 0 result[bounds[1] : bounds[2]] = 1 result[bounds[2] :, :15] = 0 result[bounds[2] :, 16:] = 2 result[labels == -100] = -1 assert np.array_equal(result >= 0, labels != -100) return result
def weights_for(source, arm): a, b = ARMS[arm] return ((source == 0) * a + (source == 1) * b + (source == 2)).astype(np.float32)
def weighted_loss(logits, labels, weights): per_token = F.cross_entropy( logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 ).view_as(labels) # Removing a source does NOT renormalize the remaining losses. return (per_token * weights).sum() / (labels != -100).sum()
class SourceGraphStep(GraphStep): def eager(self): self.optimizer.zero_grad(set_to_none=False) x, positions, mask, labels, weights = (t[self.index] for t in self.table) logits = self.model(x, position_ids=positions, attention_mask=mask) loss = weighted_loss(logits, labels, weights) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
@torch.inference_mode()def measure(model, world, table, source, device): scores, predictions = {}, {} for split in SPLITS: scores[split], pred = evaluate(model, world[split], device, composite=split != "atomic") predictions.update({split + "_" + k: v for k, v in pred.items()}) atomic = predictions["atomic_answer"] == world["atomic"][:, -1] known = {(h, r): ok for (h, r, _), ok in zip(world["atomic"], atomic, strict=True)} eligible = np.array([known[h, r1] and known[b, r2] for h, r1, b, r2, t in world["target_test"]]) full = (predictions["target_test_answer"] == world["target_test"][:, -1]) & ( predictions["target_test_stops"] == [5, 1] ).all(-1) scores["both_atomics"] = dict( n=int(eligible.sum()), coverage=float(eligible.mean()), accuracy=float(full[eligible].mean()) if eligible.any() else None, ) sums, counts = np.zeros(3), np.zeros(3, dtype=np.int64) for start in range(0, len(table[0]), 128): x, pos, mask, labels = [ torch.as_tensor(t[start : start + 128], device=device) for t in table[:4] ] logits = model(x, position_ids=pos, attention_mask=mask) nll = ( F.cross_entropy( logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 ) .view_as(labels) .cpu() .numpy() ) for group in range(3): selected = source[start : start + 128] == group sums[group] += nll[selected].sum(dtype=np.float64) counts[group] += selected.sum() scores["training_text_nll"] = { name: float(sums[i] / counts[i]) for i, name in enumerate(("atomic", "background", "neutral")) } return scores, predictions
def run(cfg, name, device): overrides = cfg["runs"][name] root = Path(cfg["output_root"]) / name if (root / "complete.json").exists(): return lock = json.loads(Path(cfg["lock"]).read_text()) for p, digest in lock["sources"].items(): assert sha(p) == digest, p assert sha(cfg["config_path"]) == lock["config_sha256"] assert sha(cfg["plan"]) == lock["plan_sha256"] for p, expected in lock["inputs"].items(): assert sha(p) == expected, p parent = Path(overrides["parent"]) assert sha(parent / "latest.pt") == lock["parents"][str(parent / "latest.pt")] root.mkdir(parents=True, exist_ok=True) state = torch.load(parent / "latest.pt", map_location=device, weights_only=False) spec = state["spec"] assert spec["arm"] == "P1" and state["step"] == 32000 world = dict(np.load(parent / "world.npz")) stored = np.load(parent / "training-table.npz") table = tuple(stored[k] for k in ("tokens", "positions", "mask", "labels")) bounds = np.cumsum( [0, len(world["atomic"]), len(world["background_train"]), len(world["target_train"])] ) source = loss_sources(table[3], bounds) weights = weights_for(source, overrides["arm"]) gpu_table = tuple(torch.as_tensor(t, device=device) for t in (*table, weights)) model = construct(spec, device) model.load_state_dict(state["model"]) opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) opt.load_state_dict(state["optimizer"]) streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] for stream, saved in zip(streams, state["streams"], strict=True): stream.load_state_dict(saved) torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) settings = dict( parent=str(parent), world=spec["world"], initialization=spec["initialization"], arm=overrides["arm"], steps=cfg["steps"], parent_sha256=sha(parent / "latest.pt"), config=cfg["config_path"], ) write_json(root / "settings.json", settings) start, elapsed, histories = 0, 0.0, [] digest = hashlib.sha256() # Recovery is deliberately from this branch's saved stream, never its parent's. if (root / "latest.pt").exists(): saved = torch.load(root / "latest.pt", map_location=device, weights_only=False) assert saved["settings"] == settings model.load_state_dict(saved["model"]) opt.load_state_dict(saved["optimizer"]) for stream, value in zip(streams, saved["streams"], strict=True): stream.load_state_dict(value) torch.set_rng_state(saved["cpu_rng"].cpu()) torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) start, elapsed, histories = saved["step"], saved["seconds"], saved["histories"] # Rebuild the hash of previously consumed paired indices from the parent state. replay = [EpochStream(bounds[i + 1] - bounds[i], 0) for i in range(3)] for stream, value in zip(replay, state["streams"], strict=True): stream.load_state_dict(value) for _ in range(start): idx = np.concatenate( [ stream.take(n) + lo for stream, n, lo in zip(replay, spec["batch_parts"], bounds[:-1], strict=True) ] ) digest.update(idx.tobytes()) initial_vector = torch.nn.utils.parameters_to_vector( [v for v in state["model"].values()] ).clone()
def checkpoint(step): metrics, predictions = measure(model, world, table, source, device) record = dict( step=step, seconds=elapsed, metrics=metrics, parameter_l2_from_source=float( torch.linalg.vector_norm( torch.nn.utils.parameters_to_vector(model.parameters()).detach() - initial_vector ) ), last_loss=None if step == 0 else float(graph.loss), last_gradient_norm=None if step == 0 else float(graph.grad_norm), ) histories.append(record) np.savez_compressed(root / f"predictions-{step:06d}.npz", **predictions) write_json(root / "learning.json", histories) model.train() current = dict( model=model.state_dict(), optimizer=opt.state_dict(), streams=[s.state_dict() for s in streams], cpu_rng=torch.get_rng_state(), cuda_rng=torch.cuda.get_rng_state(device), step=step, seconds=elapsed, histories=histories, settings=settings, ) tmp = root / "latest.tmp" torch.save(current, tmp) tmp.replace(root / "latest.pt") if step == 0 or step == cfg["steps"]: torch.save( dict(model=current["model"], step=step, settings=settings), root / f"weights-{step:06d}.pt", ) print( json.dumps( dict( run=name, step=step, target=metrics["target_test"]["accuracy"], atomic=metrics["atomic"]["accuracy"], background=metrics["background_test"]["accuracy"], ) ), flush=True, )
if start == 0: checkpoint(0) graph = SourceGraphStep(model, opt, gpu_table, sum(spec["batch_parts"])) tick = time.monotonic() for step in range(start + 1, cfg["steps"] + 1): idx = np.concatenate( [ stream.take(n) + lo for stream, n, lo in zip(streams, spec["batch_parts"], bounds[:-1], strict=True) ] ) digest.update(idx.tobytes()) graph(torch.as_tensor(idx, device=device)) if step in cfg["nodes"]: torch.cuda.synchronize() elapsed += time.monotonic() - tick checkpoint(step) tick = time.monotonic() a, b = ARMS[overrides["arm"]] write_json( root / "complete.json", dict( settings=settings, final=histories[-1], sample_trace_sha256=digest.hexdigest(), visible_supervised_tokens=cfg["steps"] * 1984, active_supervised_tokens=cfg["steps"] * (1120 * a + 288 * b + 576), estimated_flops=cfg["steps"] * flops(model.config, spec["repeats"], 128, 25, output_positions=25), checkpoint_sha256=sha(root / "latest.pt"), ), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401"""Paired full-token text pretraining with controlled cross-document access.
P0/P1 have identical token arrays and labels; only document attention changes.P2 replaces an isolated neutral record by a derived fact, an explicit change insupervision. This is controlled template-language pretraining, not a pretrainednatural-language model or a replication of the original bioS scale."""
from __future__ import annotations
import hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_model import ModelConfigfrom .grok_depth import EpochStream, GraphStep, make_optimizer, write_jsonfrom .grok_loop_model import LoopGPT, flops
WORDS = [ "<pad>", "<eos>", "<bos>", "'s", "is", ".", "This", "record", "has", "no", "additional", "fact", "here", "mentor", "advisor", "coach", "supervisor", "city", "district", "region", "campus",]LENGTH = 26PAD, EOS, BOS = 0, 1, 2
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def vocabulary(spec): return ( WORDS + [f"Person{i:03d}" for i in range(spec["heads_n"])] + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + [f"Place{i:03d}" for i in range(spec["tails_n"])] )
def atomic_sentence(row): h, r, t = map(int, row) return [BOS, h, 3, r, 4, t, 5, EOS]
def composite_sentence(row): h, r1, _b, r2, t = map(int, row) return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS]
def pack_documents(documents, groups): """Reset positions per record in every arm; BOS is an exogenous boundary.
All remaining next-token targets, including names, relations and EOS, are supervised. The next record's BOS and padding are never prediction targets. """ seq, positions, segments = [], [], [] for doc, group in zip(documents, groups, strict=True): seq.extend(doc) positions.extend(range(len(doc))) segments.extend([group] * len(doc)) if len(seq) > LENGTH: raise ValueError("Record exceeds fixed context") n = len(seq) seq += [PAD] * (LENGTH - n) positions += [0] * (LENGTH - n) segments += list(range(100, 100 + LENGTH - n)) labels = np.asarray(seq[1:], dtype=np.int64) labels[(labels == BOS) | (labels == PAD)] = -100 seg = np.asarray(segments[:-1]) mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) return ( np.asarray(seq[:-1], dtype=np.int64), np.asarray(positions[:-1], dtype=np.int64), mask[None], labels, )
def build_world(spec): """One supplied world; complete head-tail pairs held out before rendering.""" rng = np.random.default_rng(spec["world"]) hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] hs = np.arange(len(WORDS), len(WORDS) + hn) bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) lookup = {(int(h), int(r)): int(t) for h, r, t in second} paths = np.array( [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], dtype=np.int64, ) reserved = rng.random((hn, tn)) < spec["holdout_fraction"] held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] background = paths[:, 0] < hs[0] + hn // 2 groups = { "atomic_first": first, "atomic_second": second, "background_train": paths[background & ~held], "background_test": paths[background & held], "target_train": paths[~background & ~held], "target_test": paths[~background & held], } for key, rows in groups.items(): if not len(rows): raise ValueError(f"Empty world stratum {key}; do not silently reroll") train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} assert not train_pairs & test_pairs # Typed atomics can never expose a head and a tail together. assert not set(first[:, 0]) & set(second[:, 0]) assert not set(first[:, 2]) & set(second[:, 2]) groups["atomic"] = np.concatenate([first, second]) groups["all_paths"] = paths return groups
def training_table(world, arm): if arm not in ("P0", "P1", "P2"): raise ValueError(arm) packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] base_end = len(packed) packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) background_end = len(packed) neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] for row in world["target_train"]: h, r1, b, r2, t = row third = composite_sentence(row) if arm == "P2" else neutral packed.append( pack_documents( [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], [0, 1, 2] if arm == "P0" else [0, 0, 2], ) ) table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) return table, [0, base_end, background_end, len(packed)]
class TextGPT(LoopGPT): def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): if position_ids is None: position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] p = self.dropout if self.training else 0.0 x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) for layer, block in enumerate(self.iter_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), attn_mask=attention_mask, is_causal=attention_mask is None, dropout_p=p, ) attn = F.dropout( a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training ) mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) if cache is not None: cache[layer] = { "attention": attn.detach(), "mlp": mlp.detach(), "full": (x + attn + mlp).detach(), } if patch is not None and layer == patch["layer"]: pos, value, component = patch["position"], patch["value"], patch["component"] if component == "full": x = x + attn + mlp x = x.clone() x[:, pos] = value continue if component == "attention": attn = attn.clone() attn[:, pos] = value elif component == "mlp": mlp = mlp.clone() mlp[:, pos] = value else: raise ValueError(component) x = x + attn + mlp return F.linear(self.ln_final(x), self.token.weight)
class TextGraphStep(GraphStep): def eager(self): self.optimizer.zero_grad(set_to_none=False) x, positions, mask, labels = (t[self.index] for t in self.table) logits = self.model(x, position_ids=positions, attention_mask=mask) loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def construct(spec, device): torch.manual_seed(spec["initialization"]) cfg = ModelConfig( vocab_size=len(vocabulary(spec)), width=spec["width"], layers=spec["layers"], heads=spec["heads"], context=LENGTH, ) return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device)
@torch.inference_mode()def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): model.eval() encode = composite_sentence if composite else atomic_sentence prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) answers, stops, probs = [], [], [] for start in range(0, len(rows), batch_size): x = torch.as_tensor(prompts[start : start + batch_size], device=device) intervention = ( None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) ) logits = model(x, patch=intervention)[:, -1] target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) prediction = logits.argmax(-1) answers.extend(prediction.tolist()) x = torch.cat([x, prediction[:, None]], dim=1) period = model(x, patch=intervention)[:, -1].argmax(-1) x = torch.cat([x, period[:, None]], dim=1) eos = model(x, patch=intervention)[:, -1].argmax(-1) stops.extend(torch.stack([period, eos], dim=1).tolist()) ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) correct = ans == rows[:, -1] full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) return dict( n=len(rows), answer_accuracy=float(correct.mean()), accuracy=float(full.mean()), answer_probability=float(probability.mean()), ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1])
def run(spec, output, device): output = Path(output) if (output / "complete.json").exists(): return json.loads((output / "complete.json").read_text()) output.mkdir(parents=True, exist_ok=True) lock = json.loads(Path(spec["source_lock"]).read_text()) for file, expected in lock["sources"].items(): assert sha(file) == expected, file assert lock["config_sha256"] == sha(spec["config_path"]) torch.set_num_threads(2) torch.cuda.set_device(device) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_per_process_memory_fraction(0.08, device) world = build_world(spec) cpu_table, bounds = training_table(world, spec["arm"]) np.savez_compressed(output / "world.npz", **world) np.savez_compressed( output / "training-table.npz", **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, ) write_json(output / "spec.json", spec) write_json(output / "vocabulary.json", vocabulary(spec)) model = construct(spec, device) opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] latest = output / "latest.pt" start, elapsed, histories = 0, 0.0, [] if latest.exists(): state = torch.load(latest, map_location=device, weights_only=False) model.load_state_dict(state["model"]) opt.load_state_dict(state["optimizer"]) for stream, saved in zip(streams, state["streams"], strict=True): stream.load_state_dict(saved) start, elapsed, histories = state["step"], state["seconds"], state["histories"] torch.set_rng_state(state["cpu_rng"].cpu()) torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) counts = spec["batch_parts"] supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) step_flops = flops( model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 )
def checkpoint(step, seconds): metrics, predictions = {}, {} for split in ( "atomic", "background_train", "background_test", "target_train", "target_test", ): metrics[split], preds = evaluate( model, world[split], device, composite=split != "atomic" ) predictions.update({split + "_" + k: v for k, v in preds.items()}) atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] knowledge = { (int(h), int(r)): bool(ok) for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) } eligible = np.array( [ knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] for h, r1, b, r2, _t in world["target_test"] ] ) target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] metrics["target_atomic_correct"] = dict( n=int(eligible.sum()), coverage=float(eligible.mean()), answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, ) record = dict( step=step, seconds=seconds, supervised_tokens=step * supervised_per_step, estimated_flops=step * step_flops, metrics=metrics, ) histories.append(record) np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) write_json(output / "learning.json", histories) model.train() state = dict( model=model.state_dict(), optimizer=opt.state_dict(), step=step, seconds=seconds, histories=histories, spec=spec, streams=[s.state_dict() for s in streams], cpu_rng=torch.get_rng_state(), cuda_rng=torch.cuda.get_rng_state(device), ) tmp = output / "latest.tmp" torch.save(state, tmp) tmp.replace(latest) if step in spec["weight_nodes"]: torch.save( dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" ) print(json.dumps(dict(run=output.name, **record)), flush=True)
if start == 0: checkpoint(0, elapsed) model.train() graph = TextGraphStep(model, opt, table, sum(counts)) tick = time.monotonic() for step in range(start + 1, spec["steps"] + 1): idx = np.concatenate( [ stream.take(n) + offset for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) ] ) for group in opt.param_groups: group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) graph(torch.as_tensor(idx, device=device)) if step in spec["nodes"]: torch.cuda.synchronize() elapsed += time.monotonic() - tick checkpoint(step, elapsed) tick = time.monotonic() result = dict( status="complete", final=histories[-1], parameters=sum(p.numel() for p in model.parameters()), source_lock_sha256=sha(spec["source_lock"]), world_sha256=sha(output / "world.npz"), peak_memory_bytes=torch.cuda.max_memory_allocated(device), ) write_json(output / "complete.json", result) return result.gitattributes+1
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/depth_step_mechanism.pyAdded+589
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/experiment_tracking.pyAdded+289
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/experiments.pyAdded+39
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth.pyAdded+431
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_bridge.pyAdded+631
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_data.pyAdded+281
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_depth_extension.pyAdded+73
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_data.pyAdded+346
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_mechanism.pyAdded+549
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_model.pyAdded+108
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_loop_train.pyAdded+214
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_multihop.pyAdded+278
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_usage_data.pyAdded+397
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grok_usage_train.pyAdded+261
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_data.pyAdded+396
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_followup.pyAdded+103
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_future.pyAdded+148
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_interface.pyAdded+566
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_learning.pyAdded+187
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_model.pyAdded+339
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/hebbian_train.pyAdded+811
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/latent_scaling.pyAdded+311
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/latent_support.pyAdded+363
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/low_rank.pyAdded+138
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/memory_reuse.pyAdded+469
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/multihop_scaling.pyAdded+518
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/natural_composition_confirmation.pyAdded+687
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/natural_composition_confirmation_v2.pyAdded+687
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural.pyAdded+328
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural_data.pyAdded+147
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/neural_models.pyAdded+157
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_constraints.pyAdded+94
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_path_learning.pyAdded+416
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/qwen_path_train.pyAdded+627
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/recurrence_use.pyAdded+416
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/representation_alignment.pyAdded+269
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/small_lm_composition.pyAdded+543
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/small_lm_followup.pyAdded+558
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/storage_composition.pyAdded+424
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/storage_frontier.pyAdded+262
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/text_loss_source.pyAdded+256
docs/development-artifacts/bridge-workspace-v1/engineering/source/src/llm_memory_editability/text_pretrain.pyAdded+401