Archive experiment files (16/39)
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/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_model.pyAdded+108
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_train.pyAdded+214
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_multihop.pyAdded+278
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_usage_data.pyAdded+397
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_usage_train.pyAdded+261
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_data.pyAdded+396
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_followup.pyAdded+103
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_future.pyAdded+148
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_interface.pyAdded+566
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_learning.pyAdded+187
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_model.pyAdded+339
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_train.pyAdded+811
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/latent_scaling.pyAdded+311
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/latent_support.pyAdded+363
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/low_rank.pyAdded+138
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/memory_reuse.pyAdded+469
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/multihop_scaling.pyAdded+518
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/natural_composition_confirmation.pyAdded+687
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/natural_composition_confirmation_v2.pyAdded+687
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural.pyAdded+328
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural_data.pyAdded+147
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural_models.pyAdded+157
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_constraints.pyAdded+94
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_path_learning.pyAdded+416
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_path_train.pyAdded+627
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/realworld_composition.pyAdded+582
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/realworld_composition_data.pyAdded+270
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/recurrence_use.pyAdded+416
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/representation_alignment.pyAdded+269
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/small_lm_composition.pyAdded+543
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/small_lm_followup.pyAdded+558
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/storage_composition.pyAdded+424
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/storage_frontier.pyAdded+262
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_loss_source.pyAdded+256
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_pretrain.pyAdded+401
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_structure.pyAdded+432
- docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/twohop_depth.pyAdded+362
- docs/development-artifacts/realworld-composition-v1/development-source/tests/test_realworld_composition.pyAdded+289
- docs/development-artifacts/realworld-composition-v1/development-summary.jsonAdded+866
- docs/development-artifacts/realworld-composition-v1/development-validation.jsonAdded+21
- docs/development-artifacts/realworld-composition-v1/development-wandb-audit.jsonAdded+29
- docs/development-artifacts/realworld-composition-v1/preparation-audit.jsonAdded+100
89 unmodified lines90919289 unmodified linesdocs/development-artifacts/parametric-architecture-execution-v1/container/dependencies/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/parametric-architecture-execution-v1/container/dependencies/yaml/_yaml.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/qwen-path-learning-v1/pre-semantic-revision/candidates.json filter=lfs diff=lfs merge=lfs -text89 unmodified lines9091929389 unmodified linesdocs/development-artifacts/parametric-architecture-execution-v1/container/dependencies/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/parametric-architecture-execution-v1/container/dependencies/yaml/_yaml.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/qwen-path-learning-v1/pre-semantic-revision/candidates.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/shortcut-confirmation-v1/common-u/paired-common-u.csv filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582"""Complete GPT/Loop training on original 2Wiki questions and atomic facts."""
from __future__ import annotations
import copyimport hashlibimport jsonimport mathimport osimport timefrom contextlib import nullcontextfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Ffrom transformers import GPT2Config, GPT2TokenizerFast
from .grok_depth import utcfrom .grokking_reproduction import ReproductionGPT, model_digestfrom .realworld_composition_data import ( answer_scores, atomic_question, encode_example, sha256, write_json,)
def construct(config, spec, device): """Build the same eight-block reference before taking a shared prefix.""" torch.manual_seed(spec["initialization"]) options = { "vocab_size": config["vocab_size"], "n_positions": config.get("positions", 1024), "n_embd": config["hidden_size"], "n_head": config["attention_heads"], "n_layer": 8, "resid_pdrop": config["dropout"], "embd_pdrop": config["dropout"], "attn_pdrop": config["dropout"], "activation_function": "gelu_new", "use_cache": False, } model = ReproductionGPT(GPT2Config(**options), repeats=spec["repeats"]) model.transformer.h = torch.nn.ModuleList(list(model.transformer.h)[: spec["unique_layers"]]) model.config.n_layer = spec["unique_layers"] return model.to(device)
def shared_prefix_digest(model): digest = hashlib.sha256() for name, tensor in model.state_dict().items(): if name.startswith("transformer.h.") and int(name.split(".")[2]) >= 4: continue digest.update(name.encode()) digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) return digest.hexdigest()
def tensor_digests(model): return { name: hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest() for name, tensor in model.state_dict().items() }
class BatchStream: """Keep actual incomplete epoch batches, with a complete restore state."""
def __init__(self, size, seed): self.size = size self.rng = np.random.default_rng(seed) self.remaining = np.empty(0, dtype=np.int64)
def batch(self, size): if not len(self.remaining): self.remaining = self.rng.permutation(self.size) chosen, self.remaining = self.remaining[:size], self.remaining[size:] return chosen
def state_dict(self): return { "remaining": self.remaining.copy(), "rng": copy.deepcopy(self.rng.bit_generator.state), }
def load_state_dict(self, state): self.remaining = state["remaining"].copy() self.rng.bit_generator.state = copy.deepcopy(state["rng"])
def pack(records, pad, device): length = math.ceil(max(len(r["encoded"]["input"]) for r in records) / 8) * 8 targets = max(len(r["encoded"]["target"]) for r in records) tokens = np.full((len(records), length), pad, dtype=np.int64) positions = np.zeros((len(records), targets), dtype=np.int64) labels = np.full((len(records), targets), -100, dtype=np.int64) for i, record in enumerate(records): encoded = record["encoded"] tokens[i, : len(encoded["input"])] = encoded["input"] n = len(encoded["target"]) positions[i, :n] = np.arange(len(encoded["prefix"]) - 1, len(encoded["prefix"]) - 1 + n) labels[i, :n] = encoded["target"] return tuple(torch.as_tensor(a, device=device) for a in (tokens, positions, labels))
def example_losses(logits, labels): valid = labels != -100 if not bool(valid.any(dim=1).all()): raise ValueError("Every example must supervise its answer and EOS") losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as( labels ) return losses.sum(dim=1) / valid.sum(dim=1)
def optimizer_for(model, lr, decay): params = list(model.named_parameters()) groups = [ { "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, }, ] return torch.optim.AdamW( groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda )
def autocast(device): return ( torch.autocast("cuda", dtype=torch.bfloat16) if torch.device(device).type == "cuda" else nullcontext() )
def update(model, optimizer, records, spec, device, pad): model.train() optimizer.zero_grad(set_to_none=True) loss_total, executed, readout, attention = 0.0, 0, 0, 0 for start in range(0, len(records), spec["microbatch_size"]): chunk = records[start : start + spec["microbatch_size"]] tokens, positions, labels = pack(chunk, pad, device) with autocast(device): loss = example_losses(model(tokens, positions), labels).sum() / len(records) loss.backward() loss_total += float(loss.detach()) executed += tokens.numel() readout += positions.numel() attention += len(chunk) * tokens.shape[1] ** 2 norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) if not math.isfinite(loss_total) or not math.isfinite(float(norm)): raise FloatingPointError("Nonfinite loss or gradient; preserve this failure") optimizer.step() d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats flops = ( 6 * 12 * d * d * blocks * executed + 6 * d * model.config.vocab_size * readout + 12 * blocks * d * attention ) return { "loss": loss_total, "gradient_norm": float(norm), "executed_input_tokens": executed, "effective_input_tokens": sum(len(r["encoded"]["input"]) for r in records), "estimated_matmul_training_flops": flops, }
@torch.no_grad()def generate(model, prefixes, tokenizer, device, limit=64, sequence_limit=256): """Right-padded greedy generation; only the question prefix enters the model.""" model.eval() sizes = np.array([len(p) for p in prefixes], dtype=np.int64) if not len(sizes) or not (sizes > 0).all() or not (sizes <= sequence_limit).all(): raise ValueError("Generation requires nonempty prefixes within the sequence limit") budgets = np.minimum(limit, sequence_limit - sizes) tokens = torch.full( (len(prefixes), min(sequence_limit, int(sizes.max()) + limit)), tokenizer.eos_token_id, device=device, dtype=torch.long, ) for i, prefix in enumerate(prefixes): tokens[i, : len(prefix)] = torch.as_tensor(prefix, device=device) output, ended = [[] for _ in prefixes], np.zeros(len(prefixes), dtype=bool) for offset in range(limit): active = ~ended & (offset < budgets) if not active.any(): break length = min(sequence_limit, int(sizes.max()) + offset) positions = torch.as_tensor(np.minimum(sizes + offset - 1, length - 1), device=device)[ :, None ] with autocast(device): selected = model(tokens[:, :length], positions)[:, 0].argmax(-1) chosen = selected.cpu().tolist() for i, token in enumerate(chosen): if active[i]: output[i].append(token) ended[i] = token == tokenizer.eos_token_id indices = torch.as_tensor(np.flatnonzero(active), device=device) tokens[indices, torch.as_tensor(sizes[active] + offset, device=device)] = selected[indices] model.train() return [ { "prediction": tokenizer.decode( ids[:-1] if stop else ids, skip_special_tokens=True ).strip(), "generated_tokens": ids, "eos": bool(stop), "truncated": not bool(stop), "context_limit_reached": not bool(stop) and bool(len(ids) >= sequence_limit - size), "generation_limit_reached": not bool(stop) and len(ids) >= limit, } for ids, stop, size in zip(output, ended, sizes, strict=True) ]
def aggregate(predictions): fields = ["canonical_em", "alias_em", "unambiguous_alias_em", "f1", "nll", "eos", "truncated"] result = {"n": len(predictions)} for key in fields: values = [float(p[key]) for p in predictions if p[key] is not None] result[key] = sum(values) / len(values) if values else None if key == "nll": result["nll_n"] = len(values) eligible = [p for p in predictions if p.get("has_unambiguous_answer", True)] result["unambiguous_answer_coverage"] = ( len(eligible) / len(predictions) if predictions else None ) result["unambiguous_alias_em_eligible"] = ( sum(float(p["unambiguous_alias_em"]) for p in eligible) / len(eligible) if eligible else None ) result["answer_accuracy"] = result["alias_em"] return result
@torch.no_grad()def evaluate(model, records, tokenizer, device, batch_size=32): predictions = [] for start in range(0, len(records), batch_size): chunk = records[start : start + batch_size] generated = generate(model, [r["encoded"]["prefix"] for r in chunk], tokenizer, device) model.eval() tokens, positions, labels = pack(chunk, tokenizer.eos_token_id, device) with autocast(device): losses = example_losses(model(tokens, positions), labels).float().cpu().tolist() for row, result, loss in zip(chunk, generated, losses, strict=True): em, f1 = answer_scores(result["prediction"], [row["answer"], *row.get("aliases", [])]) unique_answers = row.get( "unambiguous_answers", [row["answer"], *row.get("unambiguous_aliases", [])] ) result.update( id=row["id"], canonical_em=answer_scores(result["prediction"], [row["answer"]])[0], alias_em=em, f1=f1, nll=loss, unambiguous_alias_em=answer_scores(result["prediction"], unique_answers)[0], has_unambiguous_answer=bool(unique_answers), gold=row["answer"], role=row.get("role"), required_role=row.get("required_role"), ) predictions.append(result) model.train() return aggregate(predictions), predictions
def evaluate_dataset(model, data, tokenizer, device, full=False, autonomous=False): atoms = {r["id"]: r for r in data["atoms"]} chains = {r["id"]: r for r in data["train_compositions"] + data["evaluation_compositions"]} panels = data["panels"] groups = { "atomic": list(atoms.values()) if full else [atoms[i] for i in panels["atomic"]], "train_composition": data["train_compositions"] if full else [chains[i] for i in panels["train_composition"]], } selected = ( data["evaluation_compositions"] if full else [chains[i] for name, ids in panels.items() if name.startswith("test_") for i in ids] ) groups["test_all"] = selected metrics, raw = {}, {} for name, records in groups.items(): metrics[name], raw[name] = ( evaluate(model, records, tokenizer, device) if records else (aggregate([]), []) ) lookup = {p["id"]: p for p in raw["atomic"]} for role in ["II", "IO", "OI", "OO"]: metrics["test_" + role.lower()] = aggregate( [p for p in raw["test_all"] if p["role"] == role] ) metrics["test_required_role_" + role.lower()] = aggregate( [p for p in raw["test_all"] if p["required_role"] == role] ) filters = { "test_no_known_shortcut": lambda r: not r.get("known_direct_shortcut", False), "test_head_tail_unseen": lambda r: not r.get( "head_tail_seen_in_combination_training", False ), "test_seen_operation": lambda r: r.get("operation_seen", False), "test_no_shortcut_seen_operation": lambda r: not r.get("known_direct_shortcut", False) and r.get("operation_seen", False), } for name, include in filters.items(): ids = {r["id"] for r in selected if include(r)} metrics[name] = aggregate([p for p in raw["test_all"] if p["id"] in ids]) metrics[name]["coverage"] = len(ids) / len(selected) if selected else None for index, name in enumerate(["test_first_atom", "test_second_atom"]): metrics[name] = aggregate([lookup[r["atom_ids"][index]] for r in selected]) metrics["gold_bridge_second"] = metrics["test_second_atom"].copy() prerequisite = {r["id"] for r in selected if all(lookup[a]["alias_em"] for a in r["atom_ids"])} metrics["test_prerequisites_correct"] = aggregate( [p for p in raw["test_all"] if p["id"] in prerequisite] ) metrics["test_prerequisites_correct"]["coverage"] = ( len(prerequisite) / len(selected) if selected else None ) if autonomous: second_calls = [] invalid = [] for row in selected: bridge_prediction = lookup[row["atom_ids"][0]]["prediction"] q = atomic_question(bridge_prediction, row["edges"][1][1]) try: encoded = encode_example(tokenizer, q, row["answer"]) except ValueError: invalid.append(row["id"]) continue second_calls.append( {**row, "question": q, "encoded": encoded, "autonomous_bridge": bridge_prediction} ) _, predictions = ( evaluate(model, second_calls, tokenizer, device) if second_calls else (None, []) ) for row, result in zip(second_calls, predictions, strict=True): result["bridge_prediction"] = row["autonomous_bridge"] result["second_question"] = row["question"] predictions.extend( { "id": i, "canonical_em": 0.0, "alias_em": 0.0, "unambiguous_alias_em": 0.0, "f1": 0.0, "nll": None, "eos": False, "truncated": True, "has_unambiguous_answer": False, "invalid_generated_bridge_length": True, } for i in invalid ) raw["autonomous"] = predictions metrics["autonomous"] = aggregate(predictions) metrics["autonomous"]["invalid_bridge_prompts"] = len(invalid) return metrics, raw
def save_checkpoint(path, model, optimizer, stream, counts, step, counters): temporary = Path(path).with_suffix(".tmp") torch.save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "stream": stream.state_dict(), "counts": counts, "step": step, "counters": counters, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(), }, temporary, ) temporary.replace(path)
def worker(config, spec, gpu): torch.set_num_threads(4) torch.set_num_interop_threads(1) torch.cuda.set_device(gpu) torch.backends.cuda.matmul.allow_tf32 = True device = f"cuda:{gpu}" data = json.loads(Path(config["data_file"]).read_text()) assert sha256(config["data_file"]) == config["data_sha256"] tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) out = Path(config["results_root"]) / "development" / spec["name"] out.mkdir(parents=True, exist_ok=True) model = construct(config["model"], spec, device) optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) records = data["atoms"] + data["train_compositions"] stream = BatchStream(len(records), spec["sampling_seed"]) counts = np.zeros(len(records), dtype=np.int64) counters = dict( training_seconds=0.0, examples=0, supervised_tokens=0, executed_input_tokens=0, effective_input_tokens=0, estimated_matmul_training_flops=0, ) history, initial_step, wall_offset = [], 0, 0.0 started = time.perf_counter() if (out / "latest.pt").exists(): checkpoint = torch.load(out / "latest.pt", map_location=device, weights_only=False) model.load_state_dict(checkpoint["model"]) optimizer.load_state_dict(checkpoint["optimizer"]) stream.load_state_dict(checkpoint["stream"]) counts, initial_step, counters = ( checkpoint["counts"], checkpoint["step"], checkpoint["counters"], ) torch.set_rng_state(checkpoint["cpu_rng"].cpu()) torch.cuda.set_rng_state(checkpoint["cuda_rng"].cpu()) history = [ r for r in json.loads((out / "learning.json").read_text()) if r["step"] <= initial_step ] wall_offset = history[-1]["wall_seconds"] if history else 0.0 del checkpoint else: torch.manual_seed(spec["dropout_seed"]) metadata = { "spec": spec, "world_sha256": config["data_sha256"], "initial_model_sha256": model_digest(model), "initial_tensor_sha256": tensor_digests(model), "common_four_block_initial_sha256": shared_prefix_digest(model), "parameters": sum(p.numel() for p in model.parameters()), "atomic_examples": len(data["atoms"]), "composition_examples": len(data["train_compositions"]), "vocab_size": len(tokenizer), "dtype": "BF16 AMP; FP32 parameters and Adam states", "gpu": gpu, "gpu_name": torch.cuda.get_device_name(gpu), "pid": os.getpid(), "job_type": "development-training", } write_json(out / "run.json", metadata) write_json(out / "learning.json", []) nodes = set(config["evaluation_nodes"]) last_loss = None for step in range(initial_step, spec["steps"] + 1): if step > initial_step: for group in optimizer.param_groups: group["lr"] = spec["learning_rate"] * min((step - 1) / spec["warmup_steps"], 1.0) ids = stream.batch(spec["batch_size"]) selected = [records[i] for i in ids] torch.cuda.synchronize() began = time.perf_counter() values = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) torch.cuda.synchronize() counters["training_seconds"] += time.perf_counter() - began last_loss = values["loss"] counts[ids] += 1 counters["examples"] += len(ids) counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected) for key in [ "executed_input_tokens", "effective_input_tokens", "estimated_matmul_training_flops", ]: counters[key] += values[key] if step % 50 == 0: write_json( out / "status.json", { "state": "training", "step": step, "target_step": spec["steps"], "loss": last_loss, "updated_utc": utc(), }, ) if step in nodes and not any(r["step"] == step for r in history): metrics, predictions = evaluate_dataset(model, data, tokenizer, device) write_json(out / f"predictions-{step:07d}.json", predictions) history.append( { "step": step, "metrics": metrics, **counters, "wall_seconds": wall_offset + time.perf_counter() - started, "loss": last_loss, "atomic_epochs": float(counts[: len(data["atoms"])].mean()), "composition_epochs": float(counts[len(data["atoms"]) :].mean()), "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(), "created_utc": utc(), } ) write_json(out / "learning.json", history) save_checkpoint(out / "latest.pt", model, optimizer, stream, counts, step, counters) torch.save( {"model": model.state_dict(), "step": step}, out / f"checkpoint-{step:07d}.pt" ) np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) print( json.dumps( { "step": step, "loss": last_loss, "metrics": metrics, "training_seconds": counters["training_seconds"], } ), flush=True, ) metrics, predictions = evaluate_dataset( model, data, tokenizer, device, full=True, autonomous=True ) write_json(out / "endpoint-predictions.json", predictions) write_json(out / "endpoint.json", metrics) result = { "state": "trained_pending_independent_reload", "step": spec["steps"], "pid": os.getpid(), "model_sha256": model_digest(model), "checkpoint_sha256": sha256(out / "latest.pt"), **counters, "wall_seconds": wall_offset + time.perf_counter() - started, "completed_utc": utc(), } write_json(out / "trained.json", result) write_json(out / "status.json", result)
def audit(config, spec, gpu): torch.set_num_threads(4) torch.set_num_interop_threads(1) torch.cuda.set_device(gpu) torch.backends.cuda.matmul.allow_tf32 = True device = f"cuda:{gpu}" out = Path(config["results_root"]) / "development" / spec["name"] trained = json.loads((out / "trained.json").read_text()) assert trained["pid"] != os.getpid() assert sha256(out / "latest.pt") == trained["checkpoint_sha256"] assert sha256(config["data_file"]) == config["data_sha256"] data = json.loads(Path(config["data_file"]).read_text()) tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) model = construct(config["model"], spec, device) state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) model.load_state_dict(state["model"]) assert state["step"] == spec["steps"] del state assert model_digest(model) == trained["model_sha256"] metrics, predictions = evaluate_dataset( model, data, tokenizer, device, full=True, autonomous=True ) expected = json.loads((out / "endpoint-predictions.json").read_text()) assert predictions == expected, ( "Endpoint generation or teacher-forced scores do not independently reproduce" ) assert metrics == json.loads((out / "endpoint.json").read_text()) result = { "passed": True, "pid": os.getpid(), "source_training_pid": trained["pid"], "checkpoint_sha256": trained["checkpoint_sha256"], "model_sha256": trained["model_sha256"], "predictions_recomputed": sum(len(p) for p in predictions.values()), "completed_utc": utc(), } write_json(out / "audit.json", result) write_json( out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} ) write_json( out / "status.json", {"state": "complete", "step": spec["steps"], "independently_reloaded": True}, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270"""Source-grounded 2Wiki closed-book data preparation, without model access.
Answer normalization and alias scoring follow the pinned author's v1.1 scorer.The original questions and facts are retained; this is an adapted task in whichevaluation facts may be learned separately, never with evaluation chain labels."""
from __future__ import annotations
import hashlibimport jsonimport reimport stringimport zipfilefrom collections import Counter, defaultdictfrom pathlib import Path
ARCHIVE_SHA = "95df2bf56fdabe034e27aebc580e02264232203cf52552f9efe8a919e5529eef"SPLIT_SALT = "2wiki-realworld-v1:"QUESTION_TEMPLATES = { "father": "Who is the father of {subject}?", "mother": "Who is the mother of {subject}?", "child": "Who is the child of {subject}?", "spouse": "Who is the spouse of {subject}?", "director": "Who directed {subject}?", "performer": "Who performed {subject}?", "composer": "Who composed {subject}?", "creator": "Who created {subject}?", "editor": "Who edited {subject}?", "presenter": "Who presented {subject}?", "manufacturer": "Who manufactured {subject}?", "publisher": "Who published {subject}?", "founded by": "Who founded {subject}?", "student of": "Who was the teacher of {subject}?", "educated at": "Where was {subject} educated?", "employer": "Who employed {subject}?", "date of birth": "On what date was {subject} born?", "date of death": "On what date did {subject} die?", "place of birth": "Where was {subject} born?", "place of death": "Where did {subject} die?", "place of burial": "Where was {subject} buried?", "place of detention": "Where was {subject} detained?", "cause of death": "What was the cause of death of {subject}?", "country of citizenship": "What is the country of citizenship of {subject}?", "country": "In which country is {subject}?", "inception": "On what date was {subject} established?", "award received": "What award did {subject} receive?", "has part": "What is a part of {subject}?",}
def sha256(path): result = hashlib.sha256() with Path(path).open("rb") as handle: for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): result.update(block) return result.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 order(value, salt=SPLIT_SALT): return hashlib.sha256((salt + str(value)).encode()).hexdigest()
def normalize_answer(value): value = "".join(c for c in value.lower() if c not in string.punctuation) return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split())
def answer_scores(prediction, answers): """Max EM/F1 across the author's canonical answer and entity aliases.""" p = normalize_answer(prediction) scores = [] for answer in answers: a = normalize_answer(answer) if (p in {"yes", "no", "noanswer"} or a in {"yes", "no", "noanswer"}) and p != a: f1 = 0.0 else: common = sum((Counter(p.split()) & Counter(a.split())).values()) f1 = 2 * common / (len(p.split()) + len(a.split())) if common else 0.0 scores.append((float(p == a), f1)) return max((s[0] for s in scores), default=0.0), max((s[1] for s in scores), default=0.0)
def entity_id(identifier, surface): if re.fullmatch(r"Q\d+", str(identifier)): return identifier return "literal:" + " ".join(str(surface).casefold().split())
def extract_chain(row): edges, surfaces = row.get("evidences_id", []), row.get("evidences", []) if row.get("type") != "compositional" or len(edges) != 2 or len(surfaces) != 2: return None if any(len(e) != 3 for e in edges + surfaces): return None converted = [ (entity_id(e[0], s[0]), str(e[1]), entity_id(e[2], s[2])) for e, s in zip(edges, surfaces, strict=True) ] for indices in [(0, 1), (1, 0)]: first, second = [converted[i] for i in indices] if first[2] == second[0] and first[0] != second[2]: return (first, second), [surfaces[i] for i in indices] return None
class Components: def __init__(self): self.parent = {}
def find(self, node): self.parent.setdefault(node, node) while self.parent[node] != node: self.parent[node] = self.parent[self.parent[node]] node = self.parent[node] return node
def union(self, first, second): first, second = self.find(first), self.find(second) if first != second: self.parent[max(first, second)] = min(first, second)
def support_sentences(row): context = {title: sentences for title, sentences in row["context"]} result = [] for title, index in row["supporting_facts"]: if title not in context or not 0 <= index < len(context[title]): result.append( {"title": title, "index": index, "sentence": "", "invalid_support_reference": True} ) continue result.append({"title": title, "index": index, "sentence": context[title][index]}) return result
def prior_cases(project): path = Path(project) / "docs/development-artifacts/twohop-frozen-v1/case-manifest.json" if not path.exists(): return set() return {r["id"] for r in json.loads(path.read_text()) if r["dataset"] == "2wiki"}
def extract_archive(archive, project): if sha256(archive) != ARCHIVE_SHA: raise ValueError("2Wiki archive differs from the pinned author data") records, aliases, labels = [], {}, defaultdict(Counter) groups = Components() with zipfile.ZipFile(archive) as source: for line in source.read("id_aliases.json").decode().splitlines(): entry = json.loads(line) aliases[entry["Q_id"]] = entry["aliases"] + entry.get("demonyms", []) for split in ("train", "dev"): for row in json.loads(source.read(split + ".json")): parsed = extract_chain(row) if parsed is None: continue edges, surfaces = parsed groups.union(edges[0][0], edges[0][2]) for edge, surface in zip(edges, surfaces, strict=True): labels[edge[0]][surface[0]] += 1 labels[edge[2]][surface[2]] += 1 records.append( { "id": row["_id"], "source_split": split, "question": row["question"], "answer": row["answer"], "answer_id": row.get("answer_id"), "edges": edges, "surfaces": surfaces, "support": support_sentences(row), } ) canonical = { key: sorted(counts, key=lambda s: (-counts[s], s))[0] for key, counts in labels.items() } alias_owners = defaultdict(set) for identifier, names in aliases.items(): for name in names: alias_owners[normalize_answer(name)].add(identifier) old = prior_cases(project) subject_relation = defaultdict(set) for row in records: for edge in row["edges"]: subject_relation[edge[:2]].add(edge[2]) ambiguous = {key for key, values in subject_relation.items() if len(values) > 1} for row in records: row["group"] = groups.find(row["edges"][0][0]) row["development_group"] = int(order(row["group"])[:8], 16) % 5 == 0 row["known_prior_case"] = row["id"] in old row["aliases"] = aliases.get(row["answer_id"], []) row["unambiguous_aliases"] = [ a for a in row["aliases"] if len(alias_owners[normalize_answer(a)]) == 1 ] row["structural_errors"] = [] if any(s.get("invalid_support_reference") for s in row["support"]): row["structural_errors"].append("invalid_support_sentence_reference") if any(edge[:2] in ambiguous for edge in row["edges"]): row["structural_errors"].append("multiple_objects_for_subject_relation") if row["answer_id"] and row["answer_id"] != row["edges"][1][2]: row["structural_errors"].append("answer_id_does_not_match_chain") if not row["answer_id"] and normalize_answer(row["answer"]) != normalize_answer( row["surfaces"][1][2] ): row["structural_errors"].append("literal_answer_does_not_match_chain") if any(edge[1] not in QUESTION_TEMPLATES for edge in row["edges"]): row["structural_errors"].append("unreviewed_relation_template") row["support_surface_flags"] = [] text = normalize_answer(" ".join(s["title"] + " " + s["sentence"] for s in row["support"])) for i, (edge, surface) in enumerate(zip(row["edges"], row["surfaces"], strict=True)): for j in [0, 2]: choices = [surface[j], *aliases.get(edge[j], [])] if not any(normalize_answer(c) in text for c in choices if normalize_answer(c)): row["support_surface_flags"].append( f"edge{i}_position{j}_not_literal_in_support" ) return records, aliases, canonical
def review_sample(records, size=200): """Round-robin relation pairs, then fixed hashes; independent of model scores.""" result = [] for split in ("train", "dev"): by_pair = defaultdict(list) for row in records: if row["source_split"] == split: by_pair[tuple(e[1] for e in row["edges"])].append(row) for rows in by_pair.values(): rows.sort(key=lambda r: order(r["id"], "2wiki-semantic-review-v1:")) chosen = [] while len(chosen) < size: added = False for pair in sorted(by_pair, key=lambda p: order(p, "relation-review:")): if by_pair[pair]: chosen.append(by_pair[pair].pop(0)) added = True if len(chosen) == size: break if not added: break result.extend(chosen) return result
def atomic_question(subject, relation): return QUESTION_TEMPLATES[relation].format(subject=subject)
def prompt(question): return "Question: " + question + "\nAnswer:"
def encode_example(tokenizer, question, answer, limit=256, generation_limit=64): prefix = tokenizer.encode(prompt(question), add_special_tokens=False) target = tokenizer.encode(" " + answer, add_special_tokens=False) + [tokenizer.eos_token_id] joint = tokenizer.encode(prompt(question) + " " + answer, add_special_tokens=False) if joint != prefix + target[:-1]: raise ValueError("Answer boundary changes joint tokenization") if len(prefix) + len(target) > limit or len(target) > generation_limit: raise ValueError("Example exceeds the frozen length limits; never truncate an answer") return {"prefix": prefix, "target": target, "input": (prefix + target)[:-1]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416"""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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432"""Matched relation-pair support and transfer to atomically trained facts.
Reuse the full-token text model; change composition support, not atomics,per-fact role counts, unique chain count, or token marginals. Target heads andbridges are disjoint from background; answer values are deliberately shared."""
from __future__ import annotations
import hashlibimport 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 .text_pretrain import ( LENGTH, WORDS, TextGraphStep, atomic_sentence, composite_sentence, construct, evaluate, pack_documents, sha, vocabulary,)
ARMS = ("restricted", "broad", "positive")TESTS = ("id_test", "first_only", "second_only", "background_neither", "strict_test")SPLITS = ("atomic", "train_composite", "positive_train", *TESTS)
def build_world(spec): """Balanced graph; common head-tail holdout defined before any model exists.
Each background bridge receives four trained heads per first relation. Two of its four second facts have composition experience. Restricted support pairs r1[0:2] only with even r2 and r1[2:4] only with odd r2. Broad support assigns half the incoming facts of EACH r1 to each active r2. Thus the relation-pair support has two components versus one, while all underlying first/second edge counts match exactly. """ rng = np.random.default_rng(spec["world"]) hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] if hn != 128 or bn != 32 or tn != 32: raise ValueError("This version fixes 128 heads, 32 bridges, 32 shared answer values") 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 = [] for heads, bridges in ((hs[:64], bs[:16]), (hs[64:96], bs[:16]), (hs[96:], bs[16:])): mappings = [rng.permutation(np.tile(bridges, len(heads) // len(bridges))) for _ in range(4)] first.extend((h, 13 + ri, mappings[ri][i]) for i, h in enumerate(heads) for ri in range(4)) first = np.asarray(first, dtype=np.int64) active, inactive = [], [] for bi, b in enumerate(bs[:16]): chosen = (17, 18) if bi % 2 == 0 else (19, 20) active.extend((b, r) for r in chosen) inactive.extend((b, r) for r in range(17, 21) if r not in chosen) second = [] for edges in (active, inactive, [(b, r) for b in bs[16:] for r in range(17, 21)]): tails = rng.permutation(np.tile(ts, len(edges) // len(ts))) second.extend((*edge, t) for edge, t in zip(edges, tails, strict=True)) second = np.asarray(sorted(second), 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 for r2 in range(17, 21)], dtype=np.int64, ) trained_first = first[:256] active_set = set(active) broad_assignment = {} for b in bs[:16]: choices = sorted(r for bb, r in active if bb == b) for r1 in range(13, 17): incoming = rng.permutation( trained_first[(trained_first[:, 2] == b) & (trained_first[:, 1] == r1), 0] ) if len(incoming) != 4: raise ValueError("Unbalanced graph") for i, h in enumerate(incoming): broad_assignment[int(h), r1] = choices[i // 2] trains = {} for arm in ARMS[:2]: rows = [] for h, r1, b in trained_first: choices = sorted(r for bb, r in active if bb == b) r2 = ( choices[int(r1 >= 15)] if arm == "restricted" else broad_assignment[int(h), int(r1)] ) rows.append((h, r1, b, r2, lookup[int(b), r2])) trains[arm] = np.asarray(rows, dtype=np.int64) # Two supervised paths per target person; keep the remaining head-tail # pairs for an independent positive-control generalization evaluation. positive = [] for h in hs[96:]: candidates = paths[paths[:, 0] == h] positive.extend(candidates[rng.choice(len(candidates), 2, replace=False)]) positive = np.asarray(positive, dtype=np.int64) train_union = np.concatenate([trains["restricted"], trains["broad"], positive]) pairs = {tuple(row[[0, 4]]) for row in train_union} held = np.asarray([tuple(row[[0, 4]]) not in pairs for row in paths]) first_seen = paths[:, 0] < hs[64] second_seen = np.asarray([(int(b), int(r2)) in active_set for b, r2 in paths[:, [2, 3]]]) strict = paths[:, 0] >= hs[96] world = dict( atomic=np.concatenate([first, second]), atomic_first=first, atomic_second=second, restricted_train=trains["restricted"], broad_train=trains["broad"], positive_train=positive, id_test=paths[held & first_seen & second_seen], first_only=paths[held & first_seen & ~second_seen], second_only=paths[held & ~first_seen & second_seen], background_neither=paths[held & ~first_seen & ~second_seen & ~strict], strict_test=paths[held & strict], strict_all=paths[strict], all_paths=paths, background_heads=hs[:96], background_bridges=bs[:16], target_heads=hs[96:], target_bridges=bs[16:], active_second=np.asarray(active, dtype=np.int64), ) if any(not len(world[key]) for key in TESTS): raise ValueError("Empty evaluation stratum; do not reroll worlds") return world
def role_counts(rows): return ( Counter(map(tuple, rows[:, :3])), Counter(map(tuple, rows[:, 2:])), )
def support_components(rows): adjacency = {} for _h, r1, _b, r2, _t in rows: a, b = (0, int(r1)), (1, int(r2)) adjacency.setdefault(a, set()).add(b) adjacency.setdefault(b, set()).add(a) remaining, components = set(adjacency), [] while remaining: stack, found = [min(remaining)], set() while stack: node = stack.pop() if node not in found: found.add(node) stack.extend(adjacency[node] - found) remaining -= found components.append(sorted(found)) return components
def data_audit(world): a, b = world["restricted_train"], world["broad_train"] assert len(a) == len(b) == 256 assert len(set(map(tuple, a))) == len(set(map(tuple, b))) == 256 assert role_counts(a) == role_counts(b) assert Counter(t for row in a for t in composite_sentence(row)) == Counter( t for row in b for t in composite_sentence(row) ) assert len(support_components(a)) == 2 and len(support_components(b)) == 1 lookup = {(int(h), int(r)): int(t) for h, r, t in world["atomic"]} for h, r1, bridge, r2, t in world["all_paths"]: assert lookup[int(h), int(r1)] == bridge and lookup[int(bridge), int(r2)] == t train_pairs = {tuple(r[[0, 4]]) for rows in (a, b, world["positive_train"]) for r in rows} assert all(not train_pairs & {tuple(r[[0, 4]]) for r in world[s]} for s in TESTS) assert not set(world["target_heads"]) & set( np.concatenate([a[:, 0], a[:, 2], b[:, 0], b[:, 2]]) ) assert not set(world["target_bridges"]) & set(world["background_bridges"]) assert set(world["strict_all"][:, 2]) <= set(world["target_bridges"]) first_counts, second_counts = role_counts(a) return dict( status="passed", sizes={k: len(v) for k, v in world.items()}, unique_chains={arm: len(world[arm + "_train"]) for arm in ARMS[:2]}, relation_pair_counts={ arm: np.bincount( (world[arm + "_train"][:, 1] - 13) * 4 + world[arm + "_train"][:, 3] - 17, minlength=16, ) .reshape(4, 4) .tolist() for arm in ARMS[:2] }, role_counts_match=True, token_marginals_match=True, first_edge_usage=list(sorted(set(first_counts.values()))), second_edge_usage=list(sorted(set(second_counts.values()))), common_holdout_pairs=True, isolated_target_heads_and_bridges=True, shared_answer_values=True, )
def training_table(world, arm): if arm not in ARMS: raise ValueError(arm) rows = world["restricted_train" if arm == "restricted" else "broad_train"] if arm == "positive": rows = np.concatenate([rows, world["positive_train"]]) packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] packed.extend(pack_documents([composite_sentence(r)], [0]) for r in rows) return ( tuple(np.stack([row[i] for row in packed]) for i in range(4)), [0, len(world["atomic"]), len(packed)], rows, )
def score_predictions(predictions): correct = predictions["answer"] == predictions["target"] stops = predictions["stops"] full = correct & (stops[:, 0] == 5) & (stops[:, 1] == 1) return dict( n=len(correct), answer_accuracy=float(correct.mean()), accuracy=float(full.mean()), answer_probability=float(predictions["probability"].mean()), )
@torch.inference_mode()def two_calls(model, rows, device): first = rows[:, :3] first_scores, first_pred = evaluate(model, first, device) second = np.c_[first_pred["answer"], rows[:, 3:]] _scores, pred = evaluate(model, second, device) first_stops = first_pred["stops"] format_ok = (first_stops[:, 0] == 5) & (first_stops[:, 1] == 1) second_full = ( (pred["answer"] == rows[:, -1]) & (pred["stops"][:, 0] == 5) & (pred["stops"][:, 1] == 1) ) first_ok = first_pred["answer"] == rows[:, 2] scores = score_predictions(pred) scores.update( accuracy=float((format_ok & second_full).mean()), path_accuracy=float((format_ok & first_ok & second_full).mean()), first_accuracy=first_scores["accuracy"], ) pred.update( first_answer=first_pred["answer"], first_stops=first_stops, first_target=rows[:, 2], first_probability=first_pred["probability"], ) return scores, pred
def evaluate_all(model, world, train_rows, device): metrics, predictions = {}, {} groups = dict(world, train_composite=train_rows) for split in SPLITS: scores, pred = evaluate(model, groups[split], device, composite=split != "atomic") metrics[split] = scores predictions.update({split + "_" + k: v for k, v in pred.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) } for split in TESTS: rows = world[split] eligible = np.asarray( [knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] for h, r1, b, r2, _t in rows] ) predictions[split + "_eligible"] = eligible conditional = { k: predictions[split + "_" + k][eligible] for k in ("answer", "target", "stops", "probability") } metrics[split + "_conditional"] = dict( n=int(eligible.sum()), coverage=float(eligible.mean()) ) if eligible.any(): metrics[split + "_conditional"].update(score_predictions(conditional)) else: metrics[split + "_conditional"].update( answer_accuracy=None, accuracy=None, answer_probability=None ) scores, pred = two_calls(model, rows, device) metrics[split + "_two_calls"] = scores predictions.update({split + "_two_calls_" + k: v for k, v in pred.items()}) return metrics, predictions
def verify_lock(config, source_lock): lock = json.loads(Path(source_lock).read_text()) assert lock["config_sha256"] == sha(config), config for file, expected in lock["sources"].items(): assert sha(file) == expected, file return lock
def run(spec, output, device): output = Path(output) verify_lock(spec["config_path"], spec["source_lock"]) if (output / "complete.json").exists(): return json.loads((output / "complete.json").read_text()) output.mkdir(parents=True, exist_ok=True) 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.06, device) world = build_world(spec) write_json(output / "data-audit.json", data_audit(world)) cpu_table, bounds, train_rows = training_table(world, spec["arm"]) np.savez_compressed(output / "world.npz", **world, train_composite=train_rows) 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) initial_hash = { key: hashlib.sha256(value.detach().cpu().numpy().tobytes()).hexdigest() for key, value in model.state_dict().items() } write_json(output / "initialization-hashes.json", initial_hash) 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(2)] latest = output / "latest.pt" start, elapsed, histories = 0, 0.0, [] if latest.exists(): state = torch.load(latest, map_location=device, weights_only=False) assert state["spec"] == spec 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], strict=True)) step_flops = flops( model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 ) started = utc()
def checkpoint(step, seconds): metrics, predictions = evaluate_all(model, world, train_rows, device) 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, step=step, seconds=seconds, metrics={k: metrics[k] for k in ("atomic", "train_composite", *TESTS)}, ) ), flush=True, )
if start == 0: checkpoint(0, elapsed) model.train() before = {k: v.detach().clone() for k, v in model.state_dict().items()} graph = TextGraphStep(model, opt, table, sum(counts)) assert all(torch.equal(before[k], v) for k, v in model.state_dict().items()) 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", started_utc=started, finished_utc=utc(), 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), gpu=torch.cuda.get_device_name(device), torch_version=torch.__version__, ) write_json(output / "complete.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362"""Depth, held-out composition, and bridge interventions in random fact worlds.
Entity IDs and relation IDs are disjoint. A relation is a random permutation;this makes every atom and each split's answer marginal exactly balanced."""
from __future__ import annotations
import contextlibimport hashlibimport jsonimport osfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from llm_memory_editability.bios_model import CausalLM, ModelConfig
ROOT = Path(os.environ.get("TWOHOP_PROJECT_ROOT", Path(__file__).resolve().parents[2]))CONFIG = ROOT / "configs/twohop-depth-v1.json"DATA = ROOT / "data/twohop-depth-v1"RESULTS = ROOT / "results/twohop-depth-v1"ART = ROOT / "docs/development-artifacts/twohop-depth-v1"BOS, EOS, ENTITY = 1, 2, 3
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) temp = path.with_suffix(path.suffix + ".tmp") temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") temp.replace(path)
def digest(path): h = hashlib.sha256() with Path(path).open("rb") as f: for block in iter(lambda: f.read(1024 * 1024), b""): h.update(block) return h.hexdigest()
def world_arrays(seed, cfg): n, r = cfg["entities"], cfg["relations"] if r % 2 or r < 2: raise ValueError("An even relation count is required for balanced coverage") rng = np.random.default_rng(seed) maps = np.stack([rng.permutation(n) for _ in range(r)]) # For each bridge, a regular bipartite graph over first/second relations. # Each atom occurs in r/2 training compositions in EACH hop role. orders = np.stack([rng.permutation(r) for _ in range(n)]) mask = np.zeros((n, r, r), dtype=bool) for a in range(n): for r1 in range(r): b = maps[r1, a] mask[a, r1, orders[b, (r1 + np.arange(r // 2)) % r]] = True atoms = np.array([(a, rel) for a in range(n) for rel in range(r)], dtype=np.int64) comps = np.array( [(a, r1, r2) for a in range(n) for r1 in range(r) for r2 in range(r)], dtype=np.int64, ) a, r1, r2 = comps.T bridge = maps[r1, a] answer = maps[r2, bridge] selected = rng.choice(np.flatnonzero(~mask.ravel()), cfg["diagnostic_cases"], replace=False) cases = [] inverse = np.argsort(maps, axis=1) for index in selected: a0, r10, r20 = comps[index] b0, c0 = bridge[index], answer[index] # Donor contains only a first-hop prefix; neither its explicit entity nor # its first-hop answer is the counterfactual final answer. candidates = [] for b1 in range(n): a1, c1 = inverse[r10, b1], maps[r20, b1] if b1 != b0 and c1 not in {a1, b1, a0, b0, c0}: candidates.append((int(a1), int(b1), int(c1))) if not candidates: raise ValueError("No answer-free bridge donor; increase world size") a1, b1, c1 = candidates[int(rng.integers(len(candidates)))] same_r = (r10 + 1) % r same_a = inverse[same_r, b0] wrong_candidates = [ (rr, int(maps[rr, b1])) for rr in range(r) if rr != r20 and maps[rr, b1] not in {c0, c1} ] if not wrong_candidates: raise ValueError("No distinct wrong-relation answer") wrong_r, wrong_y = wrong_candidates[int(rng.integers(len(wrong_candidates)))] cases.append([index, a0, r10, r20, b0, c0, a1, b1, c1, same_a, same_r, wrong_r, wrong_y]) ax = np.c_[np.full(len(atoms), BOS), ENTITY + atoms[:, 0], ENTITY + n + atoms[:, 1]] cx = np.c_[np.full(len(comps), BOS), ENTITY + a, ENTITY + n + r1, ENTITY + n + r2] return { "maps": maps, "atoms": atoms, "comps": comps, "train_mask": mask.ravel(), "atomic_x": ax, "atomic_y": ENTITY + maps[atoms[:, 1], atoms[:, 0]], "composite_x": cx, "composite_y": ENTITY + answer, "bridge": ENTITY + bridge, "cases": np.asarray(cases, dtype=np.int64), }
def audit_world(w, cfg): n, r = cfg["entities"], cfg["relations"] maps, comps = w["maps"], w["comps"] assert all(np.array_equal(np.sort(row), np.arange(n)) for row in maps) assert len(set(map(tuple, w["atomic_x"]))) == n * r assert len(set(map(tuple, w["composite_x"]))) == n * r * r for mask in (w["train_mask"], ~w["train_mask"]): a, r1, r2 = comps[mask].T b = maps[r1, a] assert np.all(np.bincount(a * r + r1, minlength=n * r) == r // 2) assert np.all(np.bincount(b * r + r2, minlength=n * r) == r // 2) assert np.all(np.bincount(w["composite_y"][mask] - ENTITY, minlength=n) == r * r // 2) assert np.all(~w["train_mask"][w["cases"][:, 0]]) for _, a, r1, r2, b, c, da, db, dc, sa, sr, wr, wy in w["cases"]: assert maps[r1, a] == b and maps[r2, b] == c assert maps[r1, da] == db and maps[r2, db] == dc assert maps[sr, sa] == b and sr != r1 assert dc not in {da, db, a, b, c} assert maps[wr, db] == wy and wr != r2 and wy not in {c, dc} return { "atoms": n * r, "train_compositions": int(w["train_mask"].sum()), "test_compositions": int((~w["train_mask"]).sum()), "diagnostic_cases": len(w["cases"]), "every_atom_train_composition_occurrences_per_hop": r // 2, "balanced_answers": True, "answer_free_donors": True, }
def stream_indices(length, count, rng): return np.concatenate([rng.permutation(length) for _ in range((count + length - 1) // length)])[ :count ]
def make_stream(w, seed, cfg): rng = np.random.default_rng(seed) count = cfg["steps"] * cfg["batch_per_kind"] return { "atomic": stream_indices(len(w["atomic_x"]), count, rng), "composite": stream_indices(int(w["train_mask"].sum()), count, rng), }
def build_model(arch, cfg): return CausalLM( ModelConfig( vocab_size=ENTITY + cfg["entities"] + cfg["relations"], layers=arch["layers"], width=arch["width"], heads=arch["heads"], context=8, ) )
def amp(device): return ( torch.autocast("cuda", dtype=torch.bfloat16) if str(device).startswith("cuda") else contextlib.nullcontext() )
def training_tensors(w, device): result = {} for name, mask in (("atomic", slice(None)), ("composite", w["train_mask"])): x, y = w[name + "_x"][mask], w[name + "_y"][mask] full = np.zeros((len(x), 6), dtype=np.int64) full[:, : x.shape[1]] = x full[:, x.shape[1]] = y full[:, x.shape[1] + 1] = EOS pos = np.tile([x.shape[1] - 1, x.shape[1]], (len(x), 1)) labels = np.c_[y, np.full(len(x), EOS)] result[name] = tuple(torch.as_tensor(v, device=device) for v in (full, pos, labels)) return result
def optimizer_for(model, cfg, device): decay, no_decay = [], [] for p in model.parameters(): (decay if p.ndim >= 2 else no_decay).append(p) return torch.optim.AdamW( [ {"params": decay, "weight_decay": cfg["weight_decay"]}, {"params": no_decay, "weight_decay": 0}, ], lr=cfg["lr"], betas=(0.9, 0.999), eps=1e-8, fused=str(device).startswith("cuda"), )
def train_step(model, optimizer, tensors, indices, step, cfg, device): parts = [tuple(v[indices[k]] for v in tensors[k]) for k in ("atomic", "composite")] x, pos, labels = (torch.cat([p[j] for p in parts]) for j in range(3)) lr = cfg["lr"] * min(1.0, (step + 1) / cfg["warmup"]) for group in optimizer.param_groups: group["lr"] = lr optimizer.zero_grad(set_to_none=True) with amp(device): logits = model(x, positions=pos) losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") loss = losses.mean() loss.backward() norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) optimizer.step() return loss.detach(), norm.detach()
@torch.no_grad()def predict(model, x, y, device, batch=512): pred, eos, prob = [], [], [] for start in range(0, len(x), batch): q = torch.as_tensor(x[start : start + batch], device=device) target = torch.as_tensor(y[start : start + batch], device=device) with amp(device): logits = model(q)[:, -1].float() answer = logits.argmax(-1) stop = model(torch.cat([q, answer[:, None]], dim=1))[:, -1].argmax(-1) pred.extend(answer.cpu().tolist()) eos.extend(stop.cpu().tolist()) prob.extend(logits.log_softmax(-1).gather(1, target[:, None]).squeeze(1).cpu().tolist()) return np.asarray(pred), np.asarray(eos), np.asarray(prob)
@torch.no_grad()def evaluate(model, w, cfg, device): arrays, metrics = {}, {} for name, key, mask in ( ("atomic", "atomic", slice(None)), ("train", "composite", w["train_mask"]), ("test", "composite", ~w["train_mask"]), ): x, y = w[key + "_x"][mask], w[key + "_y"][mask] pred, eos, logp = predict(model, x, y, device, cfg["eval_batch"]) arrays.update({name + "_pred": pred, name + "_eos": eos, name + "_logp": logp}) metrics.update( { name + "_answer": float(np.mean(pred == y)), name + "_exact": float(np.mean((pred == y) & (eos == EOS))), name + "_nll": float(-logp.mean()), } ) # Autonomous two-call baseline uses its own generated bridge, never the oracle. test_ids = np.flatnonzero(~w["train_mask"]) a, r1, r2 = w["comps"][test_ids].T bridge_pred = arrays["atomic_pred"][a * cfg["relations"] + r1] bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] second_x = np.c_[np.full(len(a), BOS), bridge_pred, ENTITY + cfg["entities"] + r2] y = w["composite_y"][test_ids] pred, eos, logp = predict(model, second_x, y, device, cfg["eval_batch"]) arrays.update( two_call_pred=pred, two_call_eos=eos, two_call_logp=logp, two_call_bridge=bridge_pred ) two_exact = (pred == y) & (eos == EOS) & (bridge_eos == EOS) metrics["two_call_exact"] = float(two_exact.mean()) atom_ok = (arrays["atomic_pred"] == w["atomic_y"]) & (arrays["atomic_eos"] == EOS) b = w["maps"][r1, a] both = atom_ok[a * cfg["relations"] + r1] & atom_ok[b * cfg["relations"] + r2] arrays["test_both_atoms_correct"] = both exact = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) metrics["test_both_atoms_n"] = int(both.sum()) metrics["test_given_both_atoms"] = float(exact[both].mean()) if both.any() else None return metrics, arrays
@torch.no_grad()def states_and_logits(model, tokens, device): # Mirrors bios_model.CausalLM.forward; contract-tested against ordinary forward. with amp(device): h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) states = [h.clone()] for block in model.blocks: h = block(h) states.append(h.clone()) logits = F.linear(model.ln_final(h), model.token.weight) return states, logits.float()
@torch.no_grad()def patched_logits(model, tokens, layer, positions, replacement, device): with amp(device): h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) if layer == 0: h[:, positions] = replacement.to(h.dtype) for number, block in enumerate(model.blocks, 1): h = block(h) if number == layer: h[:, positions] = replacement.to(h.dtype) return F.linear(model.ln_final(h), model.token.weight)[:, -1].float()
@torch.no_grad()def diagnostics(model, w, cfg, device): cases = w["cases"] q = torch.as_tensor(w["composite_x"][cases[:, 0]], device=device) dx = np.c_[ np.full(len(cases), BOS), ENTITY + cases[:, 6], ENTITY + cfg["entities"] + cases[:, 2] ] sx = np.c_[ np.full(len(cases), BOS), ENTITY + cases[:, 9], ENTITY + cfg["entities"] + cases[:, 10] ] clean, logits = states_and_logits(model, q, device) donor, _ = states_and_logits(model, torch.as_tensor(dx, device=device), device) same, _ = states_and_logits(model, torch.as_tensor(sx, device=device), device) old = torch.as_tensor(ENTITY + cases[:, 5], device=device) new = torch.as_tensor(ENTITY + cases[:, 8], device=device) wrong = torch.as_tensor(ENTITY + cases[:, 12], device=device) row = torch.arange(len(q), device=device) baseline = logits[:, -1] out = { "case_ids": cases[:, 0], "clean_pred": baseline.argmax(-1).cpu().numpy(), "clean_margin": (baseline[row, new] - baseline[row, old]).cpu().numpy(), "old_y": old.cpu().numpy(), "new_y": new.cpu().numpy(), "wrong_y": wrong.cpu().numpy(), } # Fixed random orthogonal coordinate permutation preserves perturbation norm. rng = np.random.default_rng(142899) perm = torch.as_tensor(rng.permutation(model.config.width), device=device) signs = torch.as_tensor(rng.choice([-1, 1], model.config.width), device=device) for layer in range(len(clean)): with amp(device): lens = F.linear(model.ln_final(clean[layer]), model.token.weight).float() out[f"lens_bridge_pos2_{layer}"] = lens[:, 2].argmax(-1).cpu().numpy() out[f"lens_query_pos3_{layer}"] = lens[:, 3].argmax(-1).cpu().numpy() delta = donor[layer][:, 2] - clean[layer][:, 2] random_state = clean[layer][:, 2] + delta[:, perm] * signs conditions = { "bridge": ([2], donor[layer][:, [2]]), "same_bridge": ([2], same[layer][:, [2]]), "random": ([2], random_state[:, None]), "source": ([1], donor[layer][:, [1]]), "prefix": ([1, 2], donor[layer][:, [1, 2]]), "identity": ([2], clean[layer][:, [2]]), } for name, (positions, replacement) in conditions.items(): z = patched_logits(model, q, layer, positions, replacement, device) prefix = f"{name}_{layer}" out[prefix + "_pred"] = z.argmax(-1).cpu().numpy() out[prefix + "_margin"] = (z[row, new] - z[row, old]).cpu().numpy() out[prefix + "_max_delta"] = (z - baseline).abs().max(-1).values.cpu().numpy() return out
def run_name(world, seed, architecture): return f"w{world}-s{seed}-{architecture}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""Scientific contracts for variable-answer, source-grounded 2Wiki training."""
import astimport copyimport reimport stringfrom collections import Counterfrom pathlib import Pathfrom types import SimpleNamespace
import numpy as npimport pytestimport torch
from llm_memory_editability import realworld_composition as rwfrom llm_memory_editability.realworld_composition_data import ( Components, answer_scores, extract_chain, normalize_answer,)
def small_config(dropout=0.0): return dict(vocab_size=31, positions=32, hidden_size=8, attention_heads=2, dropout=dropout)
def spec(layers=4, repeats=1): return dict(initialization=42, unique_layers=layers, repeats=repeats, microbatch_size=2)
def records(): return [ dict( id=str(i), encoded=dict( prefix=[1, 2, 3], target=[4] * (i % 3 + 1) + [30], input=[1, 2, 3] + [4] * (i % 3 + 1), ), ) for i in range(5) ]
def test_author_scoring_parity(): path = Path( "docs/development-artifacts/realworld-composition-v1/reference/2wikimultihop_evaluate_v1.1.py" ) tree = ast.parse(path.read_text()) selected = [ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in {"normalize_answer", "f1_score", "exact_match_score"} ] scope = dict(re=re, string=string, Counter=Counter) exec(compile(ast.Module(body=selected, type_ignores=[]), str(path), "exec"), scope) for prediction in [ "The United States", "United States.", "12 June 1516", "", "yes", "no", "New-York", "NY", ]: golds = ["United States", "U.S.", "12 June 1516", "New York", "yes"] assert normalize_answer(prediction) == scope["normalize_answer"](prediction) expected = ( max(float(scope["exact_match_score"](prediction, g)) for g in golds), max(scope["f1_score"](prediction, g)[0] for g in golds), ) assert answer_scores(prediction, golds) == expected
def test_chain_uses_ids_and_expands_literal_placeholders(): row = dict( type="compositional", evidences_id=[["Q2", "date of death", "date_information"], ["Q1", "father", "Q2"]], evidences=[["Bridge alias", "date of death", "12 June 1516"], ["Head", "father", "Bridge"]], ) edges, _ = extract_chain(row) assert edges == (("Q1", "father", "Q2"), ("Q2", "date of death", "literal:12 june 1516")) row["evidences_id"][0][0] = "Q3" assert extract_chain(row) is None
def test_grouping_joins_head_bridge_but_not_shared_tail_answers(): groups = Components() groups.union("film1", "director1") groups.union("director1", "parent1") groups.union("film2", "director2") assert groups.find("film1") == groups.find("parent1") assert groups.find("film1") != groups.find("film2")
def test_common_initialization_and_digest_do_not_change_layers(): models = [ rw.construct(small_config(), spec(layers, repeat), "cpu") for layers, repeat in [(8, 1), (4, 2), (4, 1)] ] before = [rw.model_digest(m) for m in models] assert len({rw.shared_prefix_digest(m) for m in models}) == 1 assert [len(m.transformer.h) for m in models] == [8, 4, 4] assert [rw.model_digest(m) for m in models] == before for m in models: assert ( m.transformer.wte.weight.data_ptr() == dict(m.named_parameters())["transformer.wte.weight"].data_ptr() )
def test_answer_eos_supervision_and_equal_example_weight(): x, positions, labels = rw.pack(records()[:2], 30, "cpu") assert positions[0, :2].tolist() == [2, 3] assert labels[0].tolist() == [4, 30, -100] assert x[0, :4].tolist() == [1, 2, 3, 4] logits = torch.randn(2, 3, 31, requires_grad=True) loss = rw.example_losses(logits, labels) expected = torch.stack( [ torch.nn.functional.cross_entropy( logits[i, labels[i] != -100], labels[i, labels[i] != -100] ) for i in range(2) ] ) torch.testing.assert_close(loss, expected) loss.mean().backward() assert torch.equal(logits.grad[0, 2], torch.zeros(31))
@pytest.mark.parametrize("layers,repeats", [(8, 1), (4, 2), (4, 1)])def test_causal_prefix_is_unchanged_by_future_padding(layers, repeats): model = rw.construct(small_config(), spec(layers, repeats), "cpu").eval() tokens = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8]]) baseline = model(tokens, torch.tensor([[2]])) tokens[:, 3:] = 29 torch.testing.assert_close(model(tokens, torch.tensor([[2]])), baseline, rtol=0, atol=0)
def test_partial_epoch_and_stream_restore_preserve_order(): stream = rw.BatchStream(7, 91) a, b = stream.batch(5), stream.batch(5) assert len(a) == 5 and len(b) == 2 assert sorted(np.concatenate([a, b]).tolist()) == list(range(7)) state = stream.state_dict() next_ids = stream.batch(5) restored = rw.BatchStream(7, 999) restored.load_state_dict(state) assert np.array_equal(next_ids, restored.batch(5))
def test_accumulation_matches_full_batch_with_unequal_answers(): a = rw.construct(small_config(), spec(), "cpu") b = rw.construct(small_config(), spec(), "cpu") opt_a = torch.optim.SGD(a.parameters(), lr=0.001) opt_b = torch.optim.SGD(b.parameters(), lr=0.001) full = {**spec(), "microbatch_size": 5} result_a = rw.update(a, opt_a, records(), full, "cpu", 30) result_b = rw.update(b, opt_b, records(), spec(), "cpu", 30) assert abs(result_a["loss"] - result_b["loss"]) < 1e-6 for left, right in zip(a.parameters(), b.parameters(), strict=True): torch.testing.assert_close(left, right, rtol=2e-5, atol=1e-7)
def test_dropout_adam_restore_reproduces_next_update(): model = rw.construct(small_config(0.1), spec(), "cpu") optimizer = rw.optimizer_for(model, 0.001, 0.1) rw.update(model, optimizer, records(), spec(), "cpu", 30) saved = ( copy.deepcopy(model.state_dict()), copy.deepcopy(optimizer.state_dict()), torch.get_rng_state(), ) rw.update(model, optimizer, records(), spec(), "cpu", 30) expected = copy.deepcopy(model.state_dict()) resumed = rw.construct(small_config(0.1), spec(), "cpu") resumed_opt = rw.optimizer_for(resumed, 0.001, 0.1) resumed.load_state_dict(saved[0]) resumed_opt.load_state_dict(saved[1]) torch.set_rng_state(saved[2]) rw.update(resumed, resumed_opt, records(), spec(), "cpu", 30) for key, value in resumed.state_dict().items(): torch.testing.assert_close(value, expected[key], rtol=0, atol=0)
def test_generation_receives_question_prefix_without_gold_answer(): class Model(torch.nn.Module): def forward(self, tokens, positions): assert 27 not in tokens.tolist()[0] logits = torch.zeros((len(tokens), 1, 31)) logits[:, :, 30] = 1 return logits
tokenizer = SimpleNamespace(eos_token_id=30, decode=lambda ids, **kw: str(ids)) result = rw.generate(Model(), [[1, 2, 3]], tokenizer, "cpu") assert result[0]["generated_tokens"] == [30]
def test_generation_limits_each_prompt_without_shortening_other_answers(): class Model(torch.nn.Module): def forward(self, tokens, positions): assert tokens.shape[1] <= 8 assert int(positions.max()) < tokens.shape[1] logits = torch.zeros((len(tokens), 1, 31)) logits[:, :, 5] = 1 return logits
tokenizer = SimpleNamespace(eos_token_id=30, decode=lambda ids, **kw: str(ids)) results = rw.generate(Model(), [[1] * 7, [2, 3]], tokenizer, "cpu", limit=4, sequence_limit=8) assert [len(r["generated_tokens"]) for r in results] == [1, 4] assert results[0]["context_limit_reached"] and not results[0]["eos"] assert results[1]["generation_limit_reached"] and not results[1]["context_limit_reached"]
def test_invalid_bridge_failure_does_not_lower_mean_answer_nll(): predictions = [ dict( canonical_em=1.0, alias_em=1.0, unambiguous_alias_em=1.0, f1=1.0, nll=2.0, eos=True, truncated=False, ), dict( canonical_em=0.0, alias_em=0.0, unambiguous_alias_em=0.0, f1=0.0, nll=None, eos=False, truncated=True, ), ] result = rw.aggregate(predictions) assert result["n"] == 2 and result["nll_n"] == 1 assert result["alias_em"] == 0.5 and result["nll"] == 2.0
def test_autonomous_second_call_uses_emitted_bridge(monkeypatch): seen = []
def fake_evaluate(model, items, tokenizer, device): seen.extend(r["question"] for r in items) predictions = [ dict( id=r["id"], prediction="Wrong Person", canonical_em=0.0, alias_em=0.0, unambiguous_alias_em=0.0, f1=0.0, nll=1.0, eos=True, truncated=False, role=r.get("role"), required_role=r.get("required_role"), ) for r in items ] return rw.aggregate(predictions), predictions
monkeypatch.setattr(rw, "evaluate", fake_evaluate) monkeypatch.setattr(rw, "encode_example", lambda *a: {}) atoms = [dict(id=i, question="Atomic", answer="Gold Bridge") for i in ["a", "b"]] chain = dict( id="c", question="Original question", answer="Final", atom_ids=["a", "b"], edges=[["Q1", "father", "Q2"], ["Q2", "place of birth", "Q3"]], role="OO", required_role="OO", ) data = dict( atoms=atoms, train_compositions=[], evaluation_compositions=[chain], panels=dict(atomic=["a", "b"], train_composition=[], test_oo=["c"]), ) metrics, _ = rw.evaluate_dataset(None, data, None, "cpu", autonomous=True) assert "Where was Wrong Person born?" in seen assert "Where was Gold Bridge born?" not in seen assert metrics["test_prerequisites_correct"]["coverage"] == 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866{ "development-standard8": { "atomic": { "n": 15218, "canonical_em": 0.9993428834275201, "alias_em": 0.9993428834275201, "unambiguous_alias_em": 0.874490734656328, "f1": 0.9995400183992639, "nll": 0.0007108633273445436, "nll_n": 15218, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9909317912997766, "unambiguous_alias_em_eligible": 0.8824933687002653, "answer_accuracy": 0.9993428834275201 }, "train_composition": { "n": 10870, "canonical_em": 0.9996320147194112, "alias_em": 0.9996320147194112, "unambiguous_alias_em": 0.6721251149954002, "f1": 0.999828273535725, "nll": 0.00021513804294828544, "nll_n": 10870, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9840846366145354, "unambiguous_alias_em_eligible": 0.6829952323081238, "answer_accuracy": 0.9996320147194112 }, "test_all": { "n": 2747, "canonical_em": 0.4339279213687659, "alias_em": 0.44084455769930836, "unambiguous_alias_em": 0.22388059701492538, "f1": 0.4788269672325004, "nll": 1.953396850444335, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.22777777777777777, "answer_accuracy": 0.44084455769930836 }, "test_ii": { "n": 904, "canonical_em": 0.6460176991150443, "alias_em": 0.6493362831858407, "unambiguous_alias_em": 0.34292035398230086, "f1": 0.6769806152549517, "nll": 0.8213767665604429, "nll_n": 904, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9756637168141593, "unambiguous_alias_em_eligible": 0.35147392290249435, "answer_accuracy": 0.6493362831858407 }, "test_required_role_ii": { "n": 902, "canonical_em": 0.647450110864745, "alias_em": 0.6507760532150776, "unambiguous_alias_em": 0.3436807095343681, "f1": 0.6784816809207055, "nll": 0.8145511391348809, "nll_n": 902, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.975609756097561, "unambiguous_alias_em_eligible": 0.3522727272727273, "answer_accuracy": 0.6507760532150776 }, "test_io": { "n": 300, "canonical_em": 0.23666666666666666, "alias_em": 0.24666666666666667, "unambiguous_alias_em": 0.11666666666666667, "f1": 0.2947123617123617, "nll": 2.9134882185701283, "nll_n": 300, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.96, "unambiguous_alias_em_eligible": 0.12152777777777778, "answer_accuracy": 0.24666666666666667 }, "test_required_role_io": { "n": 299, "canonical_em": 0.23745819397993312, "alias_em": 0.24749163879598662, "unambiguous_alias_em": 0.11705685618729098, "f1": 0.2956980217849783, "nll": 2.923802731212939, "nll_n": 299, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.959866220735786, "unambiguous_alias_em_eligible": 0.12195121951219512, "answer_accuracy": 0.24749163879598662 }, "test_oi": { "n": 975, "canonical_em": 0.4430769230769231, "alias_em": 0.4502564102564103, "unambiguous_alias_em": 0.22974358974358974, "f1": 0.48816052323744585, "nll": 1.6303793301088167, "nll_n": 975, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9928205128205129, "unambiguous_alias_em_eligible": 0.23140495867768596, "answer_accuracy": 0.4502564102564103 }, "test_required_role_oi": { "n": 976, "canonical_em": 0.4426229508196721, "alias_em": 0.44979508196721313, "unambiguous_alias_em": 0.22950819672131148, "f1": 0.48766035876691566, "nll": 1.6340799532337051, "nll_n": 976, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.992827868852459, "unambiguous_alias_em_eligible": 0.23116615067079463, "answer_accuracy": 0.44979508196721313 }, "test_oo": { "n": 568, "canonical_em": 0.18485915492957747, "alias_em": 0.1954225352112676, "unambiguous_alias_em": 0.08098591549295775, "f1": 0.24467778895595776, "nll": 3.8024476034732673, "nll_n": 568, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894366197183099, "unambiguous_alias_em_eligible": 0.08185053380782918, "answer_accuracy": 0.1954225352112676 }, "test_required_role_oo": { "n": 570, "canonical_em": 0.18421052631578946, "alias_em": 0.19473684210526315, "unambiguous_alias_em": 0.08070175438596491, "f1": 0.24381927039821755, "nll": 3.7932929292669533, "nll_n": 570, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894736842105263, "unambiguous_alias_em_eligible": 0.08156028368794327, "answer_accuracy": 0.19473684210526315 }, "test_no_known_shortcut": { "n": 2747, "canonical_em": 0.4339279213687659, "alias_em": 0.44084455769930836, "unambiguous_alias_em": 0.22388059701492538, "f1": 0.4788269672325004, "nll": 1.953396850444335, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.22777777777777777, "answer_accuracy": 0.44084455769930836, "coverage": 1.0 }, "test_head_tail_unseen": { "n": 2609, "canonical_em": 0.40743579915676503, "alias_em": 0.4131851284016865, "unambiguous_alias_em": 0.21847451130701417, "f1": 0.453176573011759, "nll": 2.0416101601983927, "nll_n": 2609, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9850517439632043, "unambiguous_alias_em_eligible": 0.22178988326848248, "answer_accuracy": 0.4131851284016865, "coverage": 0.9497633782307973 }, "test_seen_operation": { "n": 2744, "canonical_em": 0.43440233236151604, "alias_em": 0.4413265306122449, "unambiguous_alias_em": 0.22412536443148687, "f1": 0.4793504661033814, "nll": 1.953115273903175, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.22803114571746386, "answer_accuracy": 0.4413265306122449, "coverage": 0.9989078995267565 }, "test_no_shortcut_seen_operation": { "n": 2744, "canonical_em": 0.43440233236151604, "alias_em": 0.4413265306122449, "unambiguous_alias_em": 0.22412536443148687, "f1": 0.4793504661033814, "nll": 1.953115273903175, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.22803114571746386, "answer_accuracy": 0.4413265306122449, "coverage": 0.9989078995267565 }, "test_first_atom": { "n": 2747, "canonical_em": 0.9992719330178377, "alias_em": 0.9992719330178377, "unambiguous_alias_em": 0.9723334546778304, "f1": 0.9992719330178377, "nll": 0.0006582118829502422, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9938114306516199, "unambiguous_alias_em_eligible": 0.9783882783882784, "answer_accuracy": 0.9992719330178377 }, "test_second_atom": { "n": 2747, "canonical_em": 0.9992719330178377, "alias_em": 0.9992719330178377, "unambiguous_alias_em": 0.6792864943574809, "f1": 0.9994539497633782, "nll": 0.0003886768472457481, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6911111111111111, "answer_accuracy": 0.9992719330178377 }, "gold_bridge_second": { "n": 2747, "canonical_em": 0.9992719330178377, "alias_em": 0.9992719330178377, "unambiguous_alias_em": 0.6792864943574809, "f1": 0.9994539497633782, "nll": 0.0003886768472457481, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6911111111111111, "answer_accuracy": 0.9992719330178377 }, "test_prerequisites_correct": { "n": 2743, "canonical_em": 0.4338315712723296, "alias_em": 0.44075829383886256, "unambiguous_alias_em": 0.22384250820269777, "f1": 0.4787960915011588, "nll": 1.9541520440060416, "nll_n": 2743, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982865475756471, "unambiguous_alias_em_eligible": 0.22774480712166173, "answer_accuracy": 0.44075829383886256, "coverage": 0.9985438660356752 }, "autonomous": { "n": 2747, "canonical_em": 0.9799781579905351, "alias_em": 0.9989078995267565, "unambiguous_alias_em": 0.6792864943574809, "f1": 0.999089916272297, "nll": 0.16464137383597946, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6911111111111111, "answer_accuracy": 0.9989078995267565, "invalid_bridge_prompts": 0 } }, "development-loop4x2": { "atomic": { "n": 15218, "canonical_em": 0.999474306742016, "alias_em": 0.999540018399264, "unambiguous_alias_em": 0.874687869628072, "f1": 0.9996495378280107, "nll": 0.0007578081167703586, "nll_n": 15218, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9909317912997766, "unambiguous_alias_em_eligible": 0.8826923076923077, "answer_accuracy": 0.999540018399264 }, "train_composition": { "n": 10870, "canonical_em": 0.9998160073597057, "alias_em": 0.9998160073597057, "unambiguous_alias_em": 0.6723091076356946, "f1": 0.9998773382398038, "nll": 0.0002865202464006148, "nll_n": 10870, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9840846366145354, "unambiguous_alias_em_eligible": 0.6831822006169954, "answer_accuracy": 0.9998160073597057 }, "test_all": { "n": 2747, "canonical_em": 0.39461230433199856, "alias_em": 0.40116490717145975, "unambiguous_alias_em": 0.19585001820167455, "f1": 0.4411934948520318, "nll": 2.1686625583648103, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.19925925925925925, "answer_accuracy": 0.40116490717145975 }, "test_ii": { "n": 904, "canonical_em": 0.6139380530973452, "alias_em": 0.6183628318584071, "unambiguous_alias_em": 0.3185840707964602, "f1": 0.6402163225172075, "nll": 0.998955222381468, "nll_n": 904, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9756637168141593, "unambiguous_alias_em_eligible": 0.32653061224489793, "answer_accuracy": 0.6183628318584071 }, "test_required_role_ii": { "n": 902, "canonical_em": 0.61529933481153, "alias_em": 0.6197339246119734, "unambiguous_alias_em": 0.31929046563192903, "f1": 0.6412663217541267, "nll": 0.9959287559087828, "nll_n": 902, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.975609756097561, "unambiguous_alias_em_eligible": 0.32727272727272727, "answer_accuracy": 0.6197339246119734 }, "test_io": { "n": 300, "canonical_em": 0.18333333333333332, "alias_em": 0.19666666666666666, "unambiguous_alias_em": 0.07333333333333333, "f1": 0.2448677248677249, "nll": 3.2890475576277822, "nll_n": 300, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.96, "unambiguous_alias_em_eligible": 0.0763888888888889, "answer_accuracy": 0.19666666666666666 }, "test_required_role_io": { "n": 299, "canonical_em": 0.18394648829431437, "alias_em": 0.19732441471571907, "unambiguous_alias_em": 0.07357859531772576, "f1": 0.24568668046928918, "nll": 3.2974933482687856, "nll_n": 299, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.959866220735786, "unambiguous_alias_em_eligible": 0.07665505226480836, "answer_accuracy": 0.19732441471571907 }, "test_oi": { "n": 975, "canonical_em": 0.38769230769230767, "alias_em": 0.39384615384615385, "unambiguous_alias_em": 0.19487179487179487, "f1": 0.4321577112346343, "nll": 1.8512728414147401, "nll_n": 975, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9928205128205129, "unambiguous_alias_em_eligible": 0.1962809917355372, "answer_accuracy": 0.39384615384615385 }, "test_required_role_oi": { "n": 976, "canonical_em": 0.38729508196721313, "alias_em": 0.39344262295081966, "unambiguous_alias_em": 0.19467213114754098, "f1": 0.4320564567490797, "nll": 1.8519685387467946, "nll_n": 976, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.992827868852459, "unambiguous_alias_em_eligible": 0.19607843137254902, "answer_accuracy": 0.39344262295081966 }, "test_oo": { "n": 568, "canonical_em": 0.16901408450704225, "alias_em": 0.176056338028169, "unambiguous_alias_em": 0.06690140845070422, "f1": 0.2436424100156493, "nll": 3.9833718998725027, "nll_n": 568, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894366197183099, "unambiguous_alias_em_eligible": 0.06761565836298933, "answer_accuracy": 0.176056338028169 }, "test_required_role_oo": { "n": 570, "canonical_em": 0.16842105263157894, "alias_em": 0.17543859649122806, "unambiguous_alias_em": 0.06666666666666667, "f1": 0.24278752436647158, "nll": 3.974590359735393, "nll_n": 570, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894736842105263, "unambiguous_alias_em_eligible": 0.0673758865248227, "answer_accuracy": 0.17543859649122806 }, "test_no_known_shortcut": { "n": 2747, "canonical_em": 0.39461230433199856, "alias_em": 0.40116490717145975, "unambiguous_alias_em": 0.19585001820167455, "f1": 0.4411934948520318, "nll": 2.1686625583648103, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.19925925925925925, "answer_accuracy": 0.40116490717145975, "coverage": 1.0 }, "test_head_tail_unseen": { "n": 2609, "canonical_em": 0.36795707167497127, "alias_em": 0.3733231123035646, "unambiguous_alias_em": 0.19011115369873516, "f1": 0.41546896525815724, "nll": 2.2628835190007326, "nll_n": 2609, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9850517439632043, "unambiguous_alias_em_eligible": 0.19299610894941635, "answer_accuracy": 0.3733231123035646, "coverage": 0.9497633782307973 }, "test_seen_operation": { "n": 2744, "canonical_em": 0.39504373177842567, "alias_em": 0.40160349854227406, "unambiguous_alias_em": 0.19606413994169097, "f1": 0.44167584925602454, "nll": 2.1668958270923158, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.19948090470893584, "answer_accuracy": 0.40160349854227406, "coverage": 0.9989078995267565 }, "test_no_shortcut_seen_operation": { "n": 2744, "canonical_em": 0.39504373177842567, "alias_em": 0.40160349854227406, "unambiguous_alias_em": 0.19606413994169097, "f1": 0.44167584925602454, "nll": 2.1668958270923158, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.19948090470893584, "answer_accuracy": 0.40160349854227406, "coverage": 0.9989078995267565 }, "test_first_atom": { "n": 2747, "canonical_em": 0.9996359665089188, "alias_em": 0.9996359665089188, "unambiguous_alias_em": 0.9726974881689116, "f1": 0.9998786555029728, "nll": 0.0005872306198135241, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9938114306516199, "unambiguous_alias_em_eligible": 0.9787545787545787, "answer_accuracy": 0.9996359665089188 }, "test_second_atom": { "n": 2747, "canonical_em": 0.9992719330178377, "alias_em": 0.9992719330178377, "unambiguous_alias_em": 0.6792864943574809, "f1": 0.9996359665089188, "nll": 0.0016738464290324605, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6911111111111111, "answer_accuracy": 0.9992719330178377 }, "gold_bridge_second": { "n": 2747, "canonical_em": 0.9992719330178377, "alias_em": 0.9992719330178377, "unambiguous_alias_em": 0.6792864943574809, "f1": 0.9996359665089188, "nll": 0.0016738464290324605, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6911111111111111, "answer_accuracy": 0.9992719330178377 }, "test_prerequisites_correct": { "n": 2744, "canonical_em": 0.39504373177842567, "alias_em": 0.40160349854227406, "unambiguous_alias_em": 0.19606413994169097, "f1": 0.44155437209373105, "nll": 2.1665217703241764, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.19948090470893584, "answer_accuracy": 0.40160349854227406, "coverage": 0.9989078995267565 }, "autonomous": { "n": 2747, "canonical_em": 0.9799781579905351, "alias_em": 0.9989078995267565, "unambiguous_alias_em": 0.6789224608663997, "f1": 0.9992719330178377, "nll": 0.15933343551234208, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6907407407407408, "answer_accuracy": 0.9989078995267565, "invalid_bridge_prompts": 0 } }, "development-standard4": { "atomic": { "n": 15218, "canonical_em": 0.99967144171376, "alias_em": 0.99967144171376, "unambiguous_alias_em": 0.874885004599816, "f1": 0.999770009199632, "nll": 0.0005414011908676503, "nll_n": 15218, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9909317912997766, "unambiguous_alias_em_eligible": 0.8828912466843502, "answer_accuracy": 0.99967144171376 }, "train_composition": { "n": 10870, "canonical_em": 0.9997240110395584, "alias_em": 0.9997240110395584, "unambiguous_alias_em": 0.6722171113155474, "f1": 0.9998926709598281, "nll": 0.0006158867461662762, "nll_n": 10870, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9840846366145354, "unambiguous_alias_em_eligible": 0.6830887164625596, "answer_accuracy": 0.9997240110395584 }, "test_all": { "n": 2747, "canonical_em": 0.3924281033855115, "alias_em": 0.3993447397160539, "unambiguous_alias_em": 0.18747724790680742, "f1": 0.44394418023831994, "nll": 2.3097777620550874, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.19074074074074074, "answer_accuracy": 0.3993447397160539 }, "test_ii": { "n": 904, "canonical_em": 0.6061946902654868, "alias_em": 0.6106194690265486, "unambiguous_alias_em": 0.30420353982300885, "f1": 0.6429203539823009, "nll": 1.0381055139408886, "nll_n": 904, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9756637168141593, "unambiguous_alias_em_eligible": 0.31179138321995464, "answer_accuracy": 0.6106194690265486 }, "test_required_role_ii": { "n": 902, "canonical_em": 0.6075388026607539, "alias_em": 0.6119733924611973, "unambiguous_alias_em": 0.3048780487804878, "f1": 0.6439763488543975, "nll": 1.03716426996013, "nll_n": 902, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.975609756097561, "unambiguous_alias_em_eligible": 0.3125, "answer_accuracy": 0.6119733924611973 }, "test_io": { "n": 300, "canonical_em": 0.20333333333333334, "alias_em": 0.21666666666666667, "unambiguous_alias_em": 0.07333333333333333, "f1": 0.2632936507936509, "nll": 3.4149837497145925, "nll_n": 300, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.96, "unambiguous_alias_em_eligible": 0.0763888888888889, "answer_accuracy": 0.21666666666666667 }, "test_required_role_io": { "n": 299, "canonical_em": 0.20066889632107024, "alias_em": 0.2140468227424749, "unambiguous_alias_em": 0.07357859531772576, "f1": 0.2608297499601848, "nll": 3.4303211555105184, "nll_n": 299, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.959866220735786, "unambiguous_alias_em_eligible": 0.07665505226480836, "answer_accuracy": 0.2140468227424749 }, "test_oi": { "n": 975, "canonical_em": 0.38871794871794874, "alias_em": 0.39282051282051283, "unambiguous_alias_em": 0.18666666666666668, "f1": 0.43664263371955664, "nll": 2.0947247667253297, "nll_n": 975, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9928205128205129, "unambiguous_alias_em_eligible": 0.18801652892561985, "answer_accuracy": 0.39282051282051283 }, "test_required_role_oi": { "n": 976, "canonical_em": 0.38831967213114754, "alias_em": 0.39241803278688525, "unambiguous_alias_em": 0.1864754098360656, "f1": 0.43653678402653795, "nll": 2.092983621133092, "nll_n": 976, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.992827868852459, "unambiguous_alias_em_eligible": 0.18782249742002063, "answer_accuracy": 0.39241803278688525 }, "test_oo": { "n": 568, "canonical_em": 0.15845070422535212, "alias_em": 0.17077464788732394, "unambiguous_alias_em": 0.06338028169014084, "f1": 0.23521126760563366, "nll": 4.119120343822513, "nll_n": 568, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894366197183099, "unambiguous_alias_em_eligible": 0.06405693950177936, "answer_accuracy": 0.17077464788732394 }, "test_required_role_oo": { "n": 570, "canonical_em": 0.15964912280701754, "alias_em": 0.17192982456140352, "unambiguous_alias_em": 0.06315789473684211, "f1": 0.23614035087719282, "nll": 4.107051405504816, "nll_n": 570, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9894736842105263, "unambiguous_alias_em_eligible": 0.06382978723404255, "answer_accuracy": 0.17192982456140352 }, "test_no_known_shortcut": { "n": 2747, "canonical_em": 0.3924281033855115, "alias_em": 0.3993447397160539, "unambiguous_alias_em": 0.18747724790680742, "f1": 0.44394418023831994, "nll": 2.3097777620550874, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.19074074074074074, "answer_accuracy": 0.3993447397160539, "coverage": 1.0 }, "test_head_tail_unseen": { "n": 2609, "canonical_em": 0.36450747412801837, "alias_em": 0.3702568033729398, "unambiguous_alias_em": 0.18129551552318895, "f1": 0.4169962570115895, "nll": 2.419278079403519, "nll_n": 2609, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9850517439632043, "unambiguous_alias_em_eligible": 0.1840466926070039, "answer_accuracy": 0.3702568033729398, "coverage": 0.9497633782307973 }, "test_seen_operation": { "n": 2744, "canonical_em": 0.39285714285714285, "alias_em": 0.3997813411078717, "unambiguous_alias_em": 0.18768221574344024, "f1": 0.4444295419514085, "nll": 2.3088053696489137, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.19095291064145348, "answer_accuracy": 0.3997813411078717, "coverage": 0.9989078995267565 }, "test_no_shortcut_seen_operation": { "n": 2744, "canonical_em": 0.39285714285714285, "alias_em": 0.3997813411078717, "unambiguous_alias_em": 0.18768221574344024, "f1": 0.4444295419514085, "nll": 2.3088053696489137, "nll_n": 2744, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982871720116618, "unambiguous_alias_em_eligible": 0.19095291064145348, "answer_accuracy": 0.3997813411078717, "coverage": 0.9989078995267565 }, "test_first_atom": { "n": 2747, "canonical_em": 1.0, "alias_em": 1.0, "unambiguous_alias_em": 0.9730615216599927, "f1": 1.0, "nll": 2.1699699534975095e-05, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9938114306516199, "unambiguous_alias_em_eligible": 0.9791208791208791, "answer_accuracy": 1.0 }, "test_second_atom": { "n": 2747, "canonical_em": 0.9996359665089188, "alias_em": 0.9996359665089188, "unambiguous_alias_em": 0.6800145613396432, "f1": 0.9996359665089188, "nll": 0.0015402085372657835, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6918518518518518, "answer_accuracy": 0.9996359665089188 }, "gold_bridge_second": { "n": 2747, "canonical_em": 0.9996359665089188, "alias_em": 0.9996359665089188, "unambiguous_alias_em": 0.6800145613396432, "f1": 0.9996359665089188, "nll": 0.0015402085372657835, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6918518518518518, "answer_accuracy": 0.9996359665089188 }, "test_prerequisites_correct": { "n": 2746, "canonical_em": 0.39257101238164605, "alias_em": 0.3994901675163875, "unambiguous_alias_em": 0.18754552075746542, "f1": 0.4441058496411744, "nll": 2.3082518253333304, "nll_n": 2746, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.982884195193008, "unambiguous_alias_em_eligible": 0.1908114116339385, "answer_accuracy": 0.3994901675163875, "coverage": 0.9996359665089188 }, "autonomous": { "n": 2747, "canonical_em": 0.9807062249726974, "alias_em": 0.9996359665089188, "unambiguous_alias_em": 0.6800145613396432, "f1": 0.9996359665089188, "nll": 0.15981212766515648, "nll_n": 2747, "eos": 1.0, "truncated": 0.0, "unambiguous_answer_coverage": 0.9828904259191845, "unambiguous_alias_em_eligible": 0.6918518518518518, "answer_accuracy": 0.9996359665089188, "invalid_bridge_prompts": 0 } }}123456789101112131415161718192021{ "created_utc": "2026-10-02T19:11:18.446484+00:00", "passed": true, "frozen_configuration_sha256": "8c75acf7902acd4bd60e94cbb75c8143ba365ac43bd7def060936182ac25736a", "frozen_source_hashes_verified": true, "tests": { "new_realworld_contracts": 15, "reused_gpt_contracts": 12, "tracking_contracts": 9, "total": 36, "frozen_imports": true }, "ruff_check_and_format_passed": true, "new_section_local_links_checked": 26, "engineering_full_size_updates": 24, "tiny_restore_fixture_updates": 9, "independent_preflight_reloads": 3, "all_gpu_restore_checks_exact": true, "scientific_target_updates": 96000, "formal_training_started": false}1234567891011121314151617181920212223242526272829{ "passed": true, "runs": [ { "name": "development-loop4x2", "url": "https://wandb.ai/zhusq20/llm-memory-editability/runs/e6151e92b2272530", "state": "finished", "last_history_step": 32000, "scientific_final_step": 32000, "independently_reloaded": true }, { "name": "development-standard4", "url": "https://wandb.ai/zhusq20/llm-memory-editability/runs/68c2c3dbbe3e6d00", "state": "finished", "last_history_step": 32000, "scientific_final_step": 32000, "independently_reloaded": true }, { "name": "development-standard8", "url": "https://wandb.ai/zhusq20/llm-memory-editability/runs/5e48600d8acc087a", "state": "finished", "last_history_step": 32000, "scientific_final_step": 32000, "independently_reloaded": true } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{ "source_sha256": "95df2bf56fdabe034e27aebc580e02264232203cf52552f9efe8a919e5529eef", "candidate_sha256": "52687da8874c6a212380800049d472dc1a43ac847390cc799e3ea1620994b6f1", "semantic_packet_sha256": "0d1412ce72f660f080a1cf23955ee08fa0ec2eb608fa1e73b82702221c1dbfe5", "semantic_review_complete": false, "relations": { "father": 9411, "date of birth": 15575, "director": 48824, "country of citizenship": 14396, "composer": 7060, "place of birth": 14573, "performer": 8636, "place of burial": 893, "spouse": 7516, "date of death": 16090, "founded by": 559, "cause of death": 2134, "place of death": 10310, "mother": 2416, "educated at": 1529, "publisher": 223, "employer": 495, "child": 722, "award received": 1553, "place of detention": 13, "editor": 85, "creator": 117, "presenter": 73, "inception": 101, "country": 80, "student of": 13, "has part": 32, "manufacturer": 5 }, "splits": { "train": { "candidates": 76481, "components": 17492, "largest_components": [ [ "Q1001777", 4638 ], [ "Q100937", 892 ], [ "Q10270201", 447 ], [ "Q15043676", 352 ], [ "Q11980449", 298 ] ], "development_group_rows": 14714, "structural_error_rows": 1776, "literal_support_flag_rows": 2820, "prior_cases": 16, "review_packet_rows": 200 }, "dev": { "candidates": 5236, "components": 3359, "largest_components": [ [ "Q1001777", 74 ], [ "Q100937", 45 ], [ "Q1267706", 22 ], [ "Q102166", 21 ], [ "Q1140914", 15 ] ], "development_group_rows": 1106, "structural_error_rows": 41, "literal_support_flag_rows": 62, "prior_cases": 128, "review_packet_rows": 200 } }}.gitattributes+1
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_model.pyAdded+108
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_same_bridge.pyAdded+342
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_same_bridge_eval.pyAdded+353
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_supervision.pyAdded+349
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_loop_train.pyAdded+214
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_multihop.pyAdded+278
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_multihop_data.pyAdded+245
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_usage_data.pyAdded+397
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grok_usage_train.pyAdded+261
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grokking_dynamics_mechanism.pyAdded+421
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/grokking_reproduction.pyAdded+563
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_data.pyAdded+396
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_followup.pyAdded+103
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_future.pyAdded+148
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_interface.pyAdded+566
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_learning.pyAdded+187
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_model.pyAdded+339
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_statistics.pyAdded+168
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/hebbian_train.pyAdded+811
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/latent_scaling.pyAdded+311
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/latent_support.pyAdded+363
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/low_rank.pyAdded+138
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/memory_reuse.pyAdded+469
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/multihop_scaling.pyAdded+518
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/natural_composition_confirmation.pyAdded+687
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/natural_composition_confirmation_v2.pyAdded+687
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural.pyAdded+328
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural_data.pyAdded+147
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/neural_models.pyAdded+157
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_constraints.pyAdded+94
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_path_learning.pyAdded+416
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/qwen_path_train.pyAdded+627
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/realworld_composition.pyAdded+582
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/realworld_composition_data.pyAdded+270
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/recurrence_use.pyAdded+416
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/representation_alignment.pyAdded+269
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/small_lm_composition.pyAdded+543
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/small_lm_followup.pyAdded+558
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/storage_composition.pyAdded+424
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/storage_frontier.pyAdded+262
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_loss_source.pyAdded+256
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_pretrain.pyAdded+401
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/text_structure.pyAdded+432
docs/development-artifacts/realworld-composition-v1/development-source/src/llm_memory_editability/twohop_depth.pyAdded+362
docs/development-artifacts/realworld-composition-v1/development-source/tests/test_realworld_composition.pyAdded+289
docs/development-artifacts/realworld-composition-v1/development-summary.jsonAdded+866
docs/development-artifacts/realworld-composition-v1/development-validation.jsonAdded+21
docs/development-artifacts/realworld-composition-v1/development-wandb-audit.jsonAdded+29
docs/development-artifacts/realworld-composition-v1/preparation-audit.jsonAdded+100